I have a JSON response from an API in the following format:
string(2228) "{"question":{"type":"single","text":"Have you noticed any insects on you or have you been bitten by any insect (lice, mosquitoes, ticks, bedbugs, etc.)?",
"items":
[
{"id":"p_48","name":"Insect bite","
choices":
[{"id":"present","label":"Yes"},
{"id":"absent","label":"No"},
{"id":"unknown","label":"Don't know"}
]}
],
"extras":{}
},
"conditions":[
{"id":"c_87","name":"Common cold","common_name":"Common cold","probability":0.028},
{"id":"c_10","name":"Gastroenteritis","common_name":"Gastroenteritis","probability":0.0238},
{"id":"c_49","name":"Migraine","common_name":"Migraine","probability":0.0096}
],
"extras":{},"should_stop":false}"
I need to get the question -> text,
id and choices
&& conditions with id, name and probability.
I tried the following:
<?php
$str = file_get_contents("test.json");
//var_dump($str);
$json = json_decode($str, true);
echo '<pre>' . print_r($json, true) . '</pre>';
?>
No output. I also tried the php RecursiveArrayIterator as follows:
$jsonIterator = new RecursiveIteratorIterator(
new RecursiveArrayIterator(json_decode($json, TRUE)),
RecursiveIteratorIterator::SELF_FIRST);
foreach ($jsonIterator as $key => $val) {
if(is_array($val)) {
echo "$key:\n";
} else {
echo "$key => $val\n";
}
}
and get error message that:
Passed variable is not an array or object
I am new to php and unable to understand the reason ?? Help solicited from experts.
Update:
I called CURL directly from terminal and found that it was missing the string(2228) "and the trailing " part. So i did explode and substr. Since it is a multi-dimenisonal array i did the recursive array iterator as follows:
$jsonIterator = new RecursiveIteratorIterator(
new RecursiveArrayIterator(json_decode($str, TRUE)),
RecursiveIteratorIterator::SELF_FIRST);
foreach ($jsonIterator as $key => $val) {
if(is_array($val)) {
echo "$key:\n";
} else {
echo "$key => $val\n";
}
}
Go the output required. Issue resolved.