0

次のデータを含む文字列 ($source) があります。

{"Title":"War Horse","Year":"2011","Rated":"PG-13","Released":"25 Dec 2011","Runtime":"2 h 26 min","Genre":"Drama, War","Director":"Steven Spielberg","Writer":"Lee Hall, Richard Curtis","Actors":"Jeremy Irvine, Emily Watson, David Thewlis, Benedict Cumberbatch","Plot":"Young Albert enlists to serve in World War I after his beloved horse is sold to the cavalry. Albert's hopeful journey takes him out of England and across Europe as the war rages on.","Poster":"http://ia.media-imdb.com/images/M/MV5BMTU5MjgyNDY2NV5BMl5BanBnXkFtZTcwNjExNDc1Nw@@._V1_SX640.jpg","imdbRating":"7.2","imdbVotes":"39,540","imdbID":"tt1568911","Response":"True"}

これを使用して、タイトル、ジャンル、プロットなどを抽出しています。

foreach(str_getcsv($source) as $item) {
    list($k, $v) = explode(':', $item);
    $$k = str_replace('"', '', $v);
    }

これまでのところ、これは非常にうまく機能しており、$Title、$Genre などを使用できます。うまくいかないのはポスターの URL だけです。これは、':' を爆発させているためです。もちろん、URL には ':' ('http' の後) が含まれています。

ポスターの URL を変数に入れるにはどうすればよいですか?

4

3 に答える 3

5

それはJSONデータのように見えますが、単純ではありません。

$txt = '{"Title etc.....}';
$data = json_decode($txt);

$title = $data['Title'];
$genre = $data['Genre'];
etc...

変数変数は非常に醜く、JSONデータの内容で他の変数を上書きすることでコードを危険にさらすリスクがあります。

自動生存変数で名前空間を汚染することを本当に主張する場合は、いつでもextract()配列を引き離すために使用できます

于 2012-06-09T06:30:34.183 に答える
0

json_decodeを使用する

$str = '{"Title":"War Horse","Year":"2011","Rated":"PG-13","Released":"25 Dec 2011","Runtime":"2 h 26 min","Genre":"Drama, War","Director":"Steven Spielberg","Writer":"Lee Hall, Richard Curtis","Actors":"Jeremy Irvine, Emily Watson, David Thewlis, Benedict Cumberbatch","Plot":"Young Albert enlists to serve in World War I after his beloved horse is sold to the cavalry. Albert\'s hopeful journey takes him out of England and across Europe as the war rages on.","Poster":"http://ia.media-imdb.com/images/M/MV5BMTU5MjgyNDY2NV5BMl5BanBnXkFtZTcwNjExNDc1Nw@@._V1_SX640.jpg","imdbRating":"7.2","imdbVotes":"39,540","imdbID":"tt1568911","Response":"True"}';

$decode_string = json_decode($str);

print_r($decode_string);
echo $decode_string->Title;

これが実行中のコードですここをクリック

于 2012-06-09T06:35:42.867 に答える
0

そのjson、

json_decodeを使用する必要があります

$str = '{"Title":"War Horse","Year":"2011","Rated":"PG-13","Released":"25 Dec 2011","Runtime":"2 h 26 min","Genre":"Drama, War","Director":"Steven Spielberg","Writer":"Lee Hall, Richard Curtis","Actors":"Jeremy Irvine, Emily Watson, David Thewlis, Benedict Cumberbatch","Plot":"Young Albert enlists to serve in World War I after his beloved horse is sold to the cavalry. Albert\'s hopeful journey takes him out of England and across Europe as the war rages on.","Poster":"http://ia.media-imdb.com/images/M/MV5BMTU5MjgyNDY2NV5BMl5BanBnXkFtZTcwNjExNDc1Nw@@._V1_SX640.jpg","imdbRating":"7.2","imdbVotes":"39,540","imdbID":"tt1568911","Response":"True"}';
$arr = json_decode($str,true); 
print_r($arr);
echo $arr['Title'];
echo $arr['Year'];

文字列を適切にエスケープしたことに注意してください。

于 2012-06-09T06:37:07.210 に答える