Extracting data from JSON failed in PHP - php

{
"firstName":"sunny",
"religion": {"holly":"1",
"bolly":"colly",
"nolly":"only"
},
"lonely":"money",
"ronney":"leone",
"honey":"bunny"
}
This is my JSON. I want to get all the data from this and to be stored into some php variables or an array.
I Used the following code to extract data from my JSON. I decoded it first and then stored it in an array..
$val_array = json_decode($jsondata, true);
echo $jsondata;
$AAA = $val_array->firstName;
$BBB = $val_array->religion;
$CCC_id = $val_array->bolly;
$DDD = $val_array->nolly;
$CCC_id = $val_array->lonely;
$DDD = $val_array->ronney;
But it didn't give me any output. Then I used this.
foreach($data['val_array'] as $item)
{
echo $item[0];
}
}
No output. Help??

You get this second param wrong:
$val_array = json_decode($jsondata, true);
$AAA = $val_array['firstName'];
OR
$val_array = json_decode($jsondata, false);
$AAA=$val_array->firstName;

Your JSON is not valid. Remove commas after last elements:
{
"firstName" : "sunny",
"religion" : {
"holly" : "1",
"bolly" : "colly",
"nolly" : "only" # Here
},
"lonely" : "money",
"ronney" : "leone",
"honey" : "bunny" # And here
}

You have an error in your JSON :
"nolly":"only",
"honey":"bunny",
remove the ',' at the end of these 2 lines, then json_decode() will return you an array.
And if you want an object, do not pass second argument to json_decode()

json_decode by default returns an object yet since you are setting the second parameter to true, you are given an associative array with the information instead.
It basically comes down to the fact that either you do not need to fill in the second parameter and get the object you want, or you work with arrays when you set the parameter to true.
A little reading on PHP.net will do you good for further reference since their documentation is well presented, usually commented by others with helpful suggestions and quite clean as well!

$val_array = json_decode($jsondata, true);
$m1=$val_array['firstName'];
$m2=$val_array['lonely'];
$m3=$val_array['ronney'];
$m4=$val_array['honey'];
$m4=$val_array['religion']['holly'];
$m5=$val_array['religion']['bolly'];
$m6=$val_array['religion']['nolly'];
BY using this, we don't have to use foreach loops or inner loops for accessing data. Viola!

Related

How to read json encoded value using php?

I have a variable in PHP, named as $partialSegments. I want to iterate through it and perform actions when I strike operator or rOperandValue, etc. I receive it in a function call, so while making the
function named(say):
public function convertJsCode($partialSegments){
//logic
}
I am struggling with the logic
"segments":{"type":"custom","partialSegments":[{"type":"7","operator":11,"rOperandValue":["windows xp"],"prevLogicalOperator":null},{"type":"8","operator":11,"rOperandValue":["other"],"prevLogicalOperator":"AND"}]}}
Use json_decode() function in php
<?php
$json = '{"segments":{"type":"custom","partialSegments":[{"type":"7","operator":11,"rOperandValue":["windows xp"],"prevLogicalOperator":null},{"type":"8","operator":11,"rOperandValue":["other"],"prevLogicalOperator":"AND"}]}}';
$parsed = json_decode($json, true);
foreach($parsed["segments"]["partialSegments"] as $val) {
$operator = $val["operator"]; // operator value
$rOperandValue = $val["rOperandValue"][0]; // rOperandValue value
}
?>
Step1: convert json encoded data into php array using json_decode(); function. This function receive two arguments: first one is: json_encoded data which should be decoded and 2nd one is: boolean(TRUE or FALSE). pass second argument as TRUE to convert the json concoded values as php array, if you pass false it will return php object.
Step2: iterate php array and set the logic like a charm.
<?php
$json = '{"segments":{"type":"custom","partialSegments":[{"type":"7","operator":11,"rOperandValue":["windows xp"],"prevLogicalOperator":null},{"type":"8","operator":11,"rOperandValue":["other"],"prevLogicalOperator":"AND"}]}}';
$parsed = json_decode($json, true);
foreach($parsed as $single){
$segments = $single['partialSegments'];
//print_r($single);
foreach($segments as $segment){
echo 'operator:'. $segment['operator'].'<br>';
print_r($segment['rOperandValue']);
// put your logic based on 'operator' or 'rOperandValue'
}
}
?>
Suggestion: Don't use hard code index to work with an array like: $segment['rOperandValue'][0]. array could be empty. i.e: if you want to do anything when a value is found in $segment['rOperandValue'] use in_array().

How to get value from JSON encode in PHP?

i have searched and searched but i don't know where i'm wrong getting a value from JSON encode, can you help me? Please don't kill me, i'm a newbie :)
My php:
<?php
$data = json_decode("document.json", true);
$getit = $data["likes"];
My JSON:
[{
"title" : "MYTITLE",
"image" : "MYIMAGE",
"likes" : 0
}]
EDIT
Thanks for the help this is now working!
json_decode expects an string, not an filename - so you have first get the contents of the given file. This could be easily achieved with file_get_contents.
Your current json structure contains an array(with currently only one element), which contains an object. So if you want the likes, you have to read the first element of the result array and of that(an associative array), the likes.
$data = json_decode(file_get_contents($filename), true);
$likes = $data[0]['likes'];
If you have more than one object in the given json file, you could loop over the data with foreach
foreach ($data as $element) {
echo "likes of {$element['title']}: {$element['likes']}\n";
}
For json_decode you have to pass JSON string, not a file name. Use file_get_contents to get JSON content and then decode it.
$data = json_decode(file_get_contents('document.json'), true);
$getit = $data[0]['likes'];
Your JSON is an array of objects, you first need to access the first element of your array :
$data[0]
Then you can access the key you want :
$getit = $data[0]['likes'];
Plus, as stated in a comment above, you need to pass a string to json encode, here is an code sample that should suit your needs :
<?php
$data = json_decode(file_get_contents('document.json'), true);
$getit = $data[0]["likes"];
Hope this helps.

How to access complex JSON data in PHP

Here is the JSON response in which I need your help.
I need to access "age" key inside 'attribute'.
I really tried every possible ways that i could get. So can u please try to help me out :)
Another option, is that when you call json_decode by default you get a php object, however, if you add an optional boolean parameter you get an array which can be easier in situations like this to access nested elements.
// $data is the original json string
$json = json_decode($data, true);
print_r($json);
There are 2 ways I can see checking the json you just provided, one is by iterating the array, and the other one is accessing it by index:
$json = json_decode($response);
foreach ($json as $item) {
$value = $item->item->attribute->age->value;
var_dump($value);
}
the other way:
$value = $json[0]->item->attribute->age->value;

GET info from external Array/API/URL using PHP

I have the url http://pubapi.cryptsy.com/api.php?method=singleorderdata&marketid=132 which leads to an array.
I want to get the value of the first 'sellorders' which in this case is: 0.00000048 and store it in the variable $sellorderprice.
Can anyone help?
Thanks.
Just access the url contents thru file_get_contents. Your page actually return a JSON string, to get those values into meaningful data, decode it thru json_decode, after that access the data needed accordingly:
$url = 'http://pubapi.cryptsy.com/api.php?method=singleorderdata&marketid=132';
$data = json_decode(file_get_contents($url), true);
$sellorderprice = $data['return']['DOGE']['sellorders'][0]['price'];
echo $sellorderprice;
That code actually points directly to index zero 0 which gets the first price. If you need to get all items an just simply echo them all you need to iterate all items thru foreach:
foreach($data['return']['DOGE']['sellorders'] as $sellorders) {
echo $sellorders['price'], '<br/>';
}
Its simple, you just have to decode json like this:
$json = file_get_contents("http://pubapi.cryptsy.com/api.php?method=singleorderdata&marketid=132");
$arr = json_decode($json, true);
$sellorderprice = $arr['return']['DOGE']['sellorders'][0]['price'];

parsing a json array does not give me the values

below is my 'script.json' file with json array and i want the values of webUserid and webPassword
{
"totalSize":2,
"webUserId":"abc",
"webPassword":"def",
"operation":"send",
"testMode":true,
"records":[
{
"phoneNumber":"1908908399",
"message":"Happy Birthday",
"Id":"a0YL0000008QYunMAG",
"deviceId":"ABCDEFXABCDEF"
}
]
}
I tried below one but not getting the result
<?php
$jsonString=file_get_contents("script.json");
$decoded=json_decode($jsonString,true);
foreach($decoded->data as $name){
echo $name->totalSize;
}
?>
Zarif, try the below code, its working 100%......... :)
<?php
$jsonString=file_get_contents("script.json");
$decoded=array(json_decode($jsonString,true));
foreach($decoded as $name){
echo $name['totalSize'];
}
?>
There's no need for a foreach loop in your current example, as you only have one level.
Your main problem is you're trying to use the result of your json_decode as an object when you've previously stated you want the result as an associative array.
The 2nd param of json_decode specifies what format the return value is in, so as you've done
$decoded = json_decode($jsonString, true);
you'll receive an array, which you could access like
echo $decoded['totalSize'];
if you wanted to treat it as on object as you've done in your question, either state false or omit a 2nd param in json_decode (it's false by default anyway), and that'll let you do what you're trying to do:
$decoded = json_decode($jsonString);
$decoded->totalSize;
lets say that
$myJSON = yourPostedJSON.
$myJSON = json_decode($myJSON, true);
echo $myJSON['webUserId'];
echo $myJSON['webPassword'];

Categories