I am trying to get the contents of some source files from the same page and save them into MySQL. Some files have a different number of property names than the others so a more "auto" code will help. I am pasting below a sample source file, but you can see it live with my codes below.
Sample source file:
{
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...}
}]}
Expected output:
I want to print the properties names just once because there are the same in number for all the source file.
model_id
model_make_id
model_name
model_trim
model_year
...and so on....
------
and afterwards all the values
15155
ford
Taurus
2000
...and so on...
15073
ford
Taurus
3.0
2000
...and so on...
FIRST workaround attempt: http://codepad.viper-7.com/dZDxoo
I can print the property names and the values. But with a problem. I need only one time the property names and this is ok. But it prints only the first block of VALUES and not the other VALUES. If I can print everything, this is my solution. The number of property names from different source files I am working, are different so this helps me to get the names automatically.
<?php
$json = file_get_contents('http://www.carqueryapi.com/api/0.3/?cmd=getTrims&year=2007&make=mini');
$vres = array('{"Trims":' , '}]}');
$allakse = array("" , "}]");
$json = str_replace($vres, $allakse, $json);
$cars = json_decode($json, true);
foreach ($cars[0] as $key => $car)
{
echo "$key", "
";
}
echo"<br><br>";
foreach ($cars[0] as $key => $car)
{
echo "$car", "
";
}
SECOND workaround attempt: http://codepad.viper-7.com/7bcDUx
Because the source files have a different number of properties, having a fixed for each - echo loop
will not help me. This is essential because I want to get the property names automatically from each source file. Also, I can not print the properties names , just the values.
<?php
$json = file_get_contents('http://www.carqueryapi.com/api/0.3/?cmd=getTrims&year=2007&make=mini');
$cars = json_decode($json, true);
foreach($cars['Trims'] as $car){
echo $car['model_body'].'<br/>';
}
What should I do to echo all the values from all the blocks and not from the first only?