My json is
{"productInfoList":[{"prod":"Some Products","price":"someprice"},{"prod":"Another Product","price":"48"}]}
My php code is
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://example.com/file.json');
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
$voo = curl_exec($ch);
curl_close($ch);
$yf= json_decode($voo,true);
for ($i=0; $i < 5; $i++)
{
$fkname = $yf->{'productInfoList'}[$i]->{'prod'};
echo $i;
echo $fkname;
}
?>
Output is 012345
. How can I get product names using json?
The json file is totally fine I checked it using http://jsonviewer.stack.hu/.
asked Aug 27, 2015 at 6:02
3 Answers 3
After json_decode
, the json is converted to a php array.Try replacing this line:
$fkname = $yf->{'productInfoList'}[$i]->{'prod'};
With this line:
$fkname = $yf['productInfoList'][$i]['prod'];
Here is a working DEMO
Code Improvement
In your loop, use the array size instead of hard-coding the length:
for ($i=0; $i < sizeOf($yf['productInfoList']); $i++)
{
$fkname = $yf['productInfoList'][$i]['prod'];
echo $fkname."<BR />";
}
answered Aug 27, 2015 at 6:05
5 Comments
IdidntKnewIt
Great but if I remove true then?
IdidntKnewIt
Ok you were faster than gonzalon so you win the checkmark, upvoted both.
Luthando Ntsekwa
@IdidntKnewIt please check the demo for your code improvement
Luthando Ntsekwa
@IdidntKnewIt sorry i had a typo in my demo, please check it again
Luthando Ntsekwa
@IdidntKnewIt the browser is removing my
i++
in the demo i provide, please edit it before you run itLike this would work:
$yf= json_decode($voo,true);
$arr = $yf['productInfoList'];
for ($i=0; $i < sizeof($arr); $i++)
{
$fkname = $arr[$i]['prod'];
echo $i;
echo $fkname;
}
Take in count the sizeof
function for iterating over an array.
The output would be:
0Some Products1Another Product
Comments
use foreach
and its simple
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://example.com/file.json');
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
$voo = curl_exec($ch);
curl_close($ch);
$yf= json_decode($voo,true);
$i = 0;
foreach($yf['productInfoList'] as $product)
{
echo $i.' - '.$product['prod'].'<br />';
$i++;
}
?>
answered Aug 27, 2015 at 6:19
Comments
lang-php