Reputation: 8836
I am trying to get the content of a jSON look alike page and print all the values, as you can see in my code below.
UPDATED CODE
<?php
$json = file_get_contents('http://www.carqueryapi.com/api/0.3/?callback=?&cmd=getTrims&year=2007&make=mini');
$vres = array('?({"Trims":' , '});');
$allakse = array("" , "");
$json = str_replace($vres, $allakse, $json);
echo $json;
$cars = json_decode($json, true);
foreach ($cars[0] as $value)
{
echo $value, "<br>";
}
this is how the file looks like.
?({
Trims: [
{
"model_id":"15155"
,"model_make_id":"ford"
,"model_name":"Taurus"
,"model_trim":""
,"model_year":"2000"
,...(all available model fields are included)
},
{
"model_id":"15073"
,"model_make_id":"ford"
,"model_name":"Taurus"
,"model_trim":"3.0"
,"model_year":"2000"
,...(all available model fields are included)
},
{etc...}
]});
Even that I replaced some characters to make it look like a jSON syntax at the begining and end, I can't get it to work. What am I doing wrong?
Upvotes: 1
Views: 78
Reputation: 943635
The response is broken JSON-P, not JSON.
JSON-P consists of a function call (to a function name that you specify in the URL (?
in this case)) with data passed via the first argument.
In JSON-P, that data is supposed to be JSON. In this case, it isn't. It is a JavaScript object literal that doesn't conform to the subset that matches the JSON spec. (Specifically, you have property names expressed as identifiers instead of string literals).
You could use a JSON validator to identify the errors in the JSON response and try to clean them up (probably using some unholy set of regular expressions).
Alternatively, you could look at running a JavaScript engine (such as Node.js or Rhino), defining a function that passes the first argument to JSON.stringify()
, then prints the result (and then capturing that back into a PHP variable).
Update:
I've looked at the URL you provided. The output does not match the data in the question. The JSON does appear to be valid and without the problems your code shows it to have.
Just stop asking for callback=?
to get JSON instead of JSON-P. Then you don't need to strip off the JSON-P wrapper.
Upvotes: 1