用php错误解析json“为foreach()提供的无效参数”

时间:2012-06-12 15:48:46

标签: php json

我在使用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

1 个答案:

答案 0 :(得分:6)

json_decode的第二个参数设置为true,将JSON转换为关联数组而不是对象。

$response = json_decode($requests, true);