我在使用php解析json feed时遇到问题,无法弄清楚我做错了什么。
JSON Feed
[{"id":10428167,"url":"some_url","amount":1197,"price":0.37,"seller":{"id":4682621,"name":"Rap17ka7a"}},
{"id":10428466,"url":"some_url","amount":1450,"price":0.37,"seller":{"id":5031734,"name":"Meanor"}},
{"id":10429969,"url":"some_url","amount":109,"price":0.37,"seller":{"id":5862543,"name":"djeisanborn"}}]
PHP解析器
$request_url ="json_feed_url_is_here";
$requests = file_get_contents($request_url);
$response = json_decode($requests);
foreach ($response as $item) {
$seller = $item->seller->name;
$seller = str_replace("'", "'", $seller);
$seller = str_replace("’", "’;", $seller);
$sql = ("INSERT INTO table_name ( ~~~cell names~~~)
VALUES (~~~cell values~~~, '$item->amount', '$item->price', '$item->url')") or die('<b>Data Insert Error:</b> ' . mysql_error());
if (!mysql_query($sql,$con1))
{
die('Error: ' . mysql_error());
}
}
我得到的是这个错误:
PHP Warning: Invalid argument supplied for foreach() in path_to_php_file
答案 0 :(得分:6)
将json_decode
的第二个参数设置为true
,将JSON转换为关联数组而不是对象。
$response = json_decode($requests, true);