我一直在嘗試使用cURL和JSON在我的頁面上打印出一些JSON結果。這裏是我的代碼,因爲它剛纔站立...JSON用PHP cURL
// create curl resource
$ch = curl_init();
// set url
curl_setopt($ch, CURLOPT_URL, "http://www.wardgraphics.com/moviepickr/collection.php?user=1");
//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// $output contains the output string
$output = json_decode(curl_exec($ch));
foreach($output AS $movie) {
// echo the output
echo "<p>This movie title is: " . $movie->overview . "</p>";
}
// close curl resource to free up system resources
curl_close($ch);
當我輸出中我得到的是:
Warning: Invalid argument supplied for foreach() in /data/26/2/45/90/2371416/user/2602457/htdocs/moviepickr/tester.php on line 15
這裏有什麼東西被由php文件輸出的例子「集合?.PHP用戶= 1" :
{"title":"Shaun of the Dead","released":"2004-09-24","trailer":"http://www.youtube.com/watch?v=CfBewQPFdKE","runtime":95,"overview":"Shaun of the Dead is a humorous homage to Zombie movies from director Edgar Wright; an outrageous romantic comedy with zombies.","poster":"http://cf1.imgobject.com/posters/089/4e816b465e73d6767f000089/shaun-of-the-dead-cover.jpg"}
connection.php文件:
header('Content-type: application/json');
mysql_connect('serv', 'user', 'password');
mysql_select_db('name');
include('databasefile.php');
//'json' is set as default return format
$tmdb = new TMDb('key');
$check_collection = mysql_query("SELECT * FROM collections WHERE user_id = '$_REQUEST[user]' ORDER BY id");
while ($looped = mysql_fetch_assoc($check_collection)) {
$id = $looped[movie_id];
//Search Movie with other return format than the default
$json_movies_result = $tmdb->getMovie($id);
// Convert JSON to array of objects
$movies = json_decode($json_movies_result);
foreach ($movies AS $movie)
{
foreach($movie->posters as $poster)
{
if ($poster->image->size == 'cover') {
$poster_url = $poster->image->url;
}
}
$id = $movie->id;
$json_extra = $tmdb->getMovie($id);
$extra_info = json_decode($json_extra);
foreach($extra_info AS $extra)
{
// convert json results into new php array
$collection_array = array("title" => $movie->original_name, "released" => $movie->released, "trailer" => $extra->trailer, "runtime" => $extra->runtime, "overview" => $movie->overview, "poster" => $poster_url);
}
}
echo json_encode($collection_array);
}
這可能是簡單的爲那些你知道你的東西,讓我知道,如果它是。
謝謝!
這只是你得到的一個結果。要麼刪除該foreach。或者測試結果('is_array'),如果該API可能真的返回一個列表。 – mario
不要將curl結果直接傳遞給json_decode。如果curl中有任何類型的失敗,它將返回一個布爾值,然後解碼,然後嘗試foreach。永遠不要假設捲曲調用成功 - 總是檢查失敗。 –