I have converted an xml object returned from a php function into json format to send it to js file like.
function searchResults($q) { ...
$xml = simplexml_load_string($result);
return json_encode($xml); }
I receive/use it in js like
var msg_top = "<"+"?php echo searchResults('windows');"+"?"+">";
Then I receive it back in php & decoded.
$json = $_POST['msg_top'];
$msg = json_decode($json);
Now how do I loop through it to get all values of its certain properties that I could have get from xml object(which I converted into json). This is how I loop over xml object to get all values of its certain properties:
foreach ($xml->entry as $status) {
echo $status->author->name.''.$status->content);
}
How do I get all those values from decoded json object $msg?
EDITED
I tried in same HTML where I am using js to receive & POST php search function data via ajax, I tried following code to loop through json in php. But it did not show anything.
$obj = searchResults(testword);//serach function returns json encoded data
$obj = json_decode($obj, true);
$count = count($obj);
for($i=0;$i<$count;$i++)
{
echo $obj[$i][content];}// using xml for it, I get ouput like foreach ($xml3->entry as
// $status) {status->content}
Looping Using JSON It's a light format for storing and transferring data from one place to another. So in looping, it is one of the most commonly used techniques for transporting data that is the array format or in attribute values. Here's an example that demonstrates the above concept.
Use Object.values() or Object. entries(). These will return an array which we can then iterate over. Note that the const [key, value] = entry; syntax is an example of array destructuring that was introduced to the language in ES2015.
JSON stands for JavaScript Object Notation, and is a syntax for storing and exchanging data. Since the JSON format is a text-based format, it can easily be sent to and from a server, and used as a data format by any programming language.
By default, json_decode
returns an stdClass. stdClass-es can be used the same way as associative arrays with foreach
.
Alternatively, you can ask json_decode
to return an associative array:
$array = json_decode($_POST['foo'], TRUE);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With