Simple Json in PHP - php

I have a simple task that does not work
I Have a json file..

When you decode with the 'true' bool as second param, you will get an associative array back. In your code snippet you then loop it out.
What you should do, is skip the loop and just access the data from the assoc array right away:
echo $array['navn'];
// The JSON object:
{"nr":"5250","navn":"Odense SV","adresser":"http://oiorest.dk/danmark/postdistrikter/5250/adresser"}
// Is equivalent to this php assoc-array:
array("nr" => "5250", "navn" => "Odense SV", "adresser" => "http://oiorest.dk/danmark/postdistrikter/5250/adresser");

try following
<?php
$url = "http://oiorest.dk/danmark/postdistrikter/5000.json";
$content = file_get_contents($url);
$array = json_decode($content, true);
foreach ($array as $key=>$val) {
echo $val;
}
?>

Related

Read and print json array in php

I have a JSON array like below. I want to print only the values of the name. But I am getting undefined index name and getting value of name.below is my json.
[{"docId":{"id":"57dd70252a896558e573a0c8"},"docProfile":{"name":"gowtham","gender":null,"email":null,"mobile":"7406339908"},"docLocalInfo":{"username":"gowtham","otp":934343,"newPasswordToken":null,"tempMobile":"","adminVerfiy":null},"privateInfo":{"mciNumber":null,"aadharNumber":null,"panNumber":null},"tempHospitals":[],"bankInfo":null,"signupSteps":{"accountCreated":true,"otpValidated":true},"notification":null,"hospitals":[],"address":null}]
my code
foreach($doc_array as $data => $mydata)
{
foreach($mydata as $key=>$val)
{
echo $val['name'];
}
}
How to get the values of name from docProfile? Any help would be greatly appreciated
Inside your foreach you don't need to loop again since docProfile is an index of the json object array
Just simple access it
echo $mydata['docProfile']['name'].'<br>';
so your foreach would be like this
foreach($doc_array as $data => $mydata) {
echo $mydata['docProfile']['name'].'<br>';
}
Demo
Try to something Like this.
<?php
$string = '[{"docId":{"id":"57dd70252a896558e573a0c8"},"docProfile":{"name":"gowtham","gender":null,"email":null,"mobile":"7406339908"},"docLocalInfo":{"username":"gowtham","otp":934343,"newPasswordToken":null,"tempMobile":"","adminVerfiy":null},"privateInfo":{"mciNumber":null,"aadharNumber":null,"panNumber":null},"tempHospitals":[],"bankInfo":null,"signupSteps":{"accountCreated":true,"otpValidated":true},"notification":null,"hospitals":[],"address":null}]';
$arr = json_decode($string, true);
echo $arr[0]['docProfile']['name'];
?>
This array just have one row but if your array have more row you can use it;
you need to decode JSON at first.
$doc_array =json_decode($doc_array ,true);
foreach($doc_array as $key=> $val){
$val['docProfile']['name']
}
<?php
$json_str='[{"docId":{"id":"57dd70252a896558e573a0c8"},"docProfile":{"name":"gowtham","gender":null,"email":null,"mobile":"7406339908"},"docLocalInfo":{"username":"gowtham","otp":934343,"newPasswordToken":null,"tempMobile":"","adminVerfiy":null},"privateInfo":{"mciNumber":null,"aadharNumber":null,"panNumber":null},"tempHospitals":[],"bankInfo":null,"signupSteps":{"accountCreated":true,"otpValidated":true},"notification":null,"hospitals":[],"address":null}]';
$json_arr = (array)json_decode($json_str,true);
foreach($json_arr as $iarr => $ia)
{
foreach($ia["docProfile"] as $doc => $docDetails)
{
if($doc =="name")
{
echo $ia["docProfile"]["name"];
}
}
}
?>
This code gives you the answer

PHP foreach json_encode issues

I got problems with json_encode.
My code below:
$jsonfiles = array('http://example.com/myjsonishere.php'); //Here's my JSON
foreach ( $jsonfiles as $jsonfile ) {
//read the json file contents
$jsondata = file_get_contents($jsonfile);
//convert json object to php associative array
$data = json_decode($jsondata, true);
$json = json_decode(stripslashes($data));
foreach ((array)$json as $u => $z){
foreach ($z as $n => $line){
//get the tweet details
$grap_item1 = $line['grap1'];
$grap_item2 = $line['grap2'];
$grap_item3 = $line['grap3'];
// execute this insertion
mysqli_stmt_execute($stmt);
}
}
}
Without that stripslashes, json_last_error would show error number 4 but now it's 0, so I'm good to go.
Without (array) in first foreach PHP error pop up:
Invalid foreach argument
Even if I have tested after $json = json_decode(stripslashes($data)); line : if(is_array($json)) the test is TRUE but still the foreach will not work without (array)
Anyway, in theory, my code passes the first foreach, but if I put inside first foreach loop e.g. var_dumb($z) or whatever, it will not print anything. So I guess my code is stuck in the first foreach.
Please, let me know if I could provide more information.

How to get JSON response in to PHP variables

I am getting following response in JSON format and I want it to convert it into PHP variables.
JSON:
{"CreateTransactionResponse":{"CreateTransactionResult":{"TransportKey":"aa900d54-7bfb-47e9-a5de-e423ec34a900"
,"ValidationKey":"fbb28b32-f439-4801-a434-99c70aa388ca","Messages":{}}}}
output should be PHP:
$transkey = aa900d54-7bfb-47e9-a5de-e423ec34a900;
$vkey = fbb28b32-f439-4801-a434-99c70aa388ca
please advice me how to do it.
Just simply use json_decode();
$result= json_decode($jSon);
var_dump($result); // to see the output
json to array(json_decode) and then extract from array.
$arr = json_decode($json, true);
extract($arr);
var_dump($CreateTransactionResponse);
Output:
array (size=1)
'CreateTransactionResult' =>
array (size=3)
'TransportKey' => string 'aa900d54-7bfb-47e9-a5de-e423ec34a900' (length=36)
'ValidationKey' => string 'fbb28b32-f439-4801-a434-99c70aa388ca' (length=36)
'Messages' =>
array (size=0)
empty
More about extract
use $CreateTransactionResult['TransportKey'] to access Transport Key from JSON. Similarly $CreateTransactionResult['ValidationKey'] for Validation Key.
If you want to access your json try to decode it first:
$result = json_decode($yourJSON, true);
foreach($result['CreateTransactionResponse'] as $key => $val){
echo $transkey = 'TransportKey= ' . $val['TransportKey'] . '<br/>;
echo $vkey = 'ValidationKey= ' . $val['ValidationKey'];
}
Or if it is an array of JSON's
$result = json_decode($yourJSON, true);
$data = [];
foreach($result['CreateTransactionResponse'] as $key => $val){
$data[] = [
'TransportKey' => $val['TransportKey'],
'ValidationKey' => $val['ValidationKey']
];
}
print_r($data);
try this code it will work
$JSON='{"CreateTransactionResponse":{"CreateTransactionResult":{"TransportKey":"aa900d54-7bfb-47e9-a5de-e423ec34a900" ,"ValidationKey":"fbb28b32-f439-4801-a434-99c70aa388ca","Messages":{}}}}';
$arr=json_decode($JSON, TRUE);
foreach ($arr as $value) {
foreach ($arr['CreateTransactionResponse'] as $key => $var) {
echo 'TransportKey = '.$var['TransportKey'].'<br>';
echo 'ValidationKey = '.$var['ValidationKey'].'<br>';
foreach ($var['Messages'] as $key => $msg) {
echo 'Messages = '.$msg.'<br>';
}
}
}
In this case,If its a single and TransportKey and a single ValidationKey value (not an array/object is passed) at a time, this is the simplest. Else if object contains objects or inside objects that we want to use or convert to variable, should use a foreach to loop through the object.
//Debuggig
//The string you provided is converted to a json object
//In your case if it is a json object already pass directly it to $j
//below is just for debugging and understanding
//$json='{"CreateTransactionResponse":{"CreateTransactionResult":{"TransportKey":"aa900d54-7bfb-47e9-a5de-e423ec34a900","ValidationKey":"fbb28b32-f439-4801-a434-99c70aa388ca","Messages":{}}}}';
//$j=json_decode($json);
$transkey=$j->CreateTransactionResponse->CreateTransactionResult->TransportKey;
$vkey=$j->CreateTransactionResponse->CreateTransactionResult->ValidationKey;
echo $transkey."</br>";
echo $vkey."<br/>";
/*result as said:
aa900d54-7bfb-47e9-a5de-e423ec34a900
fbb28b32-f439-4801-a434-99c70aa388ca
*/

PHP Cannot loop through nested JSON

I have an API which is returning some nested JSON data with multiple levels. My PHP code to loop through is below but I'm not getting any output:
$data = json_decode($output, true);
foreach($data as $item){
$title = $item->events->name->text;
echo $title;
}
An example of the data can be found here: http://i.imgur.com/Y55vl7n.png
I am trying to print the text name of each of the events (events->name->text)
There is a problem in your code, when you decode the json string, you use:
$data = json_decode($output, true);
It is converting everything to "array" (http://php.net/manual/en/function.json-decode.php), so you cannot access it like if they were objects.
You have to do:
foreach($data as $item){
$title = $item["events"]["name"]["text"];
echo $title;
}
Hope this helps!

json_encode particular part of array

$array = array("Real" => array("Alonso","Zidan"),"Inter" => "Zanetti", "Roma" => "Toti");
$json=json_encode($array);
echo $json
By this way I am reading all the data, but how can I read the data of
only Real or Inter?
For example, if it is json_decoded I can do so:
For Inter:
echo $array['Inter'];
For Real:
foreach($array["Real"] as $real){
echo $real."<br>";
}
How can I do the same with json_encode()?
json_encode() returns a string, so you can't access its parts without parsing the string. But you can do the following instead:
echo json_encode($array['Inter']);
As I understand your question you need to output the json`d object.
Input
$input = '{"Real":["Alonso","Zidan"],"Inter":"Zanetti","Roma":"Toti"}';
In php:
// Second true is for array return, not object)
$string = json_decode($input, true)
echo $string['Inter'];
In Javascript (jQuery):
var obj = jQuery.parseJSON(input);
if (obj != undefined) {
echo obj['Inter'];
}
UPD:
If you need to get an json in all arrays you need to make follow:
$array = array("Real" => array("Alonso","Zidan"),"Inter" => "Zanetti", "Roma" => "Toti");
foreach($array as $key => $value) {
$array[$key] = json_encode($value);
}
After this code all variables in array will be json`ed and you can echo them in any time

Categories