Usage of json_encode and json_decode - php

I am new to PHP. I am using json_encode to convert an array into json data, and decode it using json_decode in another file. However, I am getting json error as syntax error.
My code is as follows:
File 1:
$result = get_data_array();
exit(json_encode($result));
File 2:
$result = file_get_contents("http://localhost/file1.php");
$data = json_decode($result,true);
$data->name // name is the array key
However, I am getting an error as:
Trying to get property of non-object.

You passed true to the second parameter of json_decode so it will return an array.
Use this:
$result = file_get_contents("http://localhost/file1.php");
$data = json_decode($result,true);
echo $data['name'];

Related

Get values from JSON array using PHP

I run the following PHP after I submit a form and get the output shown below:
$data = json_encode($_POST);
// output
{"First_Name":"Fred"}
How do I use PHP to just display the value 'Fred'?
I tried echo $data['First_Name']; but this is blank.
You no need to encode your incoming $_POST data.
Just say:
echo $_POST['First_Name'];
If you get a json data, decode it into an array:
$data = '{"First_Name":"Fred"}';
$decoded = json_decode($data, true);
echo $decoded['First_name'];
First of all, don't know why you use json_encode on PHP Array, and try to access it like it's an array - because after json_encode it's a string.
You have to use json_decode($data, true) and then you can access it like $data['First_Name'] or try to access it directly without json_encode() by $_POST['First_Name']
The json_decode() function is used to decode or convert a JSON object to a PHP object.And try to put the object to decode in another variable to avoid errors
<?php
$obj = '{"First_Name":"Fred"}';
$data = json_decode($obj);
echo ($data->First_Name);
?>

How to take out int value from JSON object?

I'm working with Laravel 5 right now and I have the following problem. I've got response from DB query:
[{"id":1}]
and I want to take out 1 as int or string. Any ideas?
I've tried to solve this like follows:
$json = (DB query);
$data = json_decode($json);
$final = $data[0]->id;
and response is :
json_decode() expects parameter 1 to be string, array given
This is all you need.
$response = json_decode($response); // Decode the JSON
$string = $response[0]->id; // Save the value of id var
As you say, the string you have is in JSON format, so you need to use json_decode to access it in PHP.
The square brackets refer to an array, and the braces refer to an object within that array, so what you're looking for is the id value of the first element (i.e. element 0) in the array.
<?php
$json = '[{"id":1}]';
$data = json_decode($json);
echo $data[0]->id;
// 1
Try this
$json_array = '[{"id":1}]';
$data = json_decode($json_array);
print_r($data); // To display the result array
You just need to decode it, if I'm not misunderstanding your questions.
$json = '[{"id":1}]';
$decodedObject = json_decode($json);
Then you can loop through the aray and do something with your data:
foreach($decodedObject as $key => $value) {
$id = $value->id;
}
If you're using Laravel, though, why not use Eloquent models?

PHP json_Encode an array of json_encode-ed arrays

Im not sure what is happening, but if i do
json_encode()
On a single array, i get valid json, but if i do something like
$ar['key'] = "name";
$array[] = json_encode($ar);
$json = json_encode($array);
It will return invalid json like so:
["{"key":"name"}"]
The expected outcome is
[{"key":"name"}]
I have searched for hours trying to find what is going on.
Due to lack of desired outcome, I can only assume you are trying to get a multidimensional array.
The correct way to achieve this would be to build an array of arrays, and then json_encode the parent array.
$data = array();
$data['fruits'] = array('apple','banana','cherry');
$data['animals'] = array('dog', 'elephant');
$json = json_encode($data);
Following this code, $json will have the following value
{"fruits":["apple","banana","cherry"],"animals":["dog","elephant"]}
It could then be parsed properly by javascript using jQuery.parseJSON()
Just json_encode the entire array.
$ar['key'] = "name";
$json = json_encode($ar);
json_encode returns a string, and json encoding a string will return a string.
Also it's json_encode, not $json_encode

Error Parsing JSON file with PHP

I have a string like this:
{
"update_id":659510742,
"message":{
"message_id":178,
"from":{
"id":110910409,
"first_name":"S.M_Emamian"
},
"chat":{
"id":-57184742,
"title":"Vvggg",
"type":"group"
},
"date":1446970836,
"new_chat_participant":{
"id":131677747,
"first_name":"Shadyab",
"username":"Shadyabbot"
}
}
}
now, I would like to get first_name. how can I get that ?
I tested below code, but it doesn't work :
$json_a = json_decode($content, true);
$first_name = $json_a->message->from->first_name; //it returns nothing.
$json_a = json_decode($content, true);
^^^^
That true forces the output of json_decode to be an array, but you are trying to treat it like an object. Remove that argument or use array syntax:
$first_name = $json_a['message']['from']['first_name'];
use only json_decode($content) remove true
try this code :-
$json_a = json_decode($content);
echo $json_a->message->from->first_name;
True convert the output of json_decode to be an array
$json_a = json_decode($content, true);
$first_name = $json_a->message->from->first_name; //it returns nothing.
That's because the function returns an associative array, and not an object.
By using -> you're trying to access object properties of $json_a. What you're really looking for is:
$json_a["message"]["from"]["first_name"]
This way you're accessing the associative array values by their key, and not trying to access object properties.
I hope this helped,
Sebastian
$json_a = json_decode($content);
$first_name = $json_a->message->from->first_name;
or
$json_a = json_decode($content,true);
$first_name = $json_a[message][from][first_name];
You're passing true as the second argument to json_decode which tells it to return an associative array rather than an object.
Either remove the second argument (or change it to the default, false), or access the fields using array syntax:
$first_name = $json['message']['from']['first_name'];
json_decode() is a php function used to decode json into either php standard object or an associative array dependent upon argument passed to it
When true it will return an associative otherwise by default it returns standard PHP object
According to your requirement please try executing following code snippet for retrieving first name from json document.
$json_a = json_decode($content, true);
$first_name = $json_a['message']['from']['first_name'];
For more detailed description regarding parsing json documents in php please refer the documentation in following URL
http://php.net/manual/en/function.json-decode.php

Reading multiple json values with php

I am trying to read certain values from a json string in php, I am able to do a simple json string with only one value such as
$json = '{"value":"somevalue"}';
Using this:
<?php
$json = '{"value":"somevalue"}';
$obj = json_decode(json_encode($json));
print $obj->{'value'};
?>
But when i try an get a value from the following json string it throws an error...
$json = '{"field": "title","rule": {"required": "true","minlength": "4","maxlength": "150" }}';
I validated the json on JSONlint but not sure how to access the values within this with php.
Thanks
You can try this:
$json = '{"field": "title","rule": {"required": "true","minlength": "4","maxlength": "150" }}';
//since $json is a valid json format you needn't encode and decode it again
$obj = json_decode($json);
print_r($obj->filed);
print_r($obj->rule);
You can pass true as a second parameter to json_decode() to get the results as an array
$my_arr = json_decode($json, true);
var_dump($my_arr);
Should help you. You can then step through the array as you would normally.
use var_dump to print out the object with all it's members and hierarchy. you should then be able to find the value you are looking for

Categories