2

I have a problem with parsing a json feed with php and can not figure out what I am doing wrong.

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 parser

$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());
  }
}

What I get is this error:

PHP Warning:  Invalid argument supplied for foreach() in path_to_php_file
3
  • Var_dump the result for debugging. Show a hex excerpt of the file start. Commented Jun 12, 2012 at 15:57
  • Your php seems ok, var_dump the $requests. Commented Jun 12, 2012 at 15:58
  • var_dump($requests); gives normal data output Commented Jun 12, 2012 at 16:11

1 Answer 1

6

Set the second argument of json_decode to true to convert the JSON to associative array instead of object.

$response = json_decode($requests, true);
Sign up to request clarification or add additional context in comments.

4 Comments

it is already an array, because it is wrapped by []. I confirm this by running the code.
@ariefbayu you're right, the result is an array of object. The original code should be ok.
@milenmk check if the JSON only contains a single element so its not wrapped in []. e.g: {"id":10428167,"url":"some_url","amount":1197,"price":0.37,"seller":{"id":4682621,"name":"Rap17ka7a"}.
@bsdnoobz, all 10 elements are inside the []

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.