2

我在用 php 解析 json 提要时遇到问题,无法弄清楚我做错了什么。

JSON 提要

[{"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
4

1 回答 1

6

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

$response = json_decode($requests, true);
于 2012-06-12T15:50:11.327 回答