Can't figure out JSON formatting for PHP - php

[{"text":"\n $3.99\n ","attrs":{"class":"priceLarge"}}]
This is how JSON is being returned to me... (using print_r($price) to display)...
I have tried various ways in PHP to access this data, but nothing has worked.
I want the "text"...
Thanks!
EDIT:
var_dump (as requested)
string(96) "[{"text":"\n $3.99\n ","attrs":{"class":"priceLarge"}}]"

Make use of json_decode()
<?php
$jsonStr='[{"text":"\n $3.99\n ","attrs":{"class":"priceLarge"}}]';
$jsonArr = json_decode($jsonStr);
echo $jsonArr[0]->text;

Assuming that you've got a JSON string, you need to use json_decode() to translate it into a PHP object first:
$json = json_decode($jsonString);
From there, you can access text from the first object in the data (which is an array, defined by the outer square brackets[]:
echo $json[0]->text;
// | |
// | The property text of that first element.
// |
// The first element in the array of data.

$string = '[{"text":"\n $3.99\n ","attrs":{"class":"priceLarge"}}]';
$obj = json_decode($string);
Allowing you to access:
print $obj[0]->text;

Related

how to fetch json fom url in php

I am trying to make a php page tp print json data for this i m using one paraeter for which i needed to fetch json from another url.I used the code given in other stackoverflow ans but it always giving 0.I tried everything but it always giving 0.My php code is:
<?php
if(isset($_POST['add']))
{
require_once('loginConnect.php');
$bookname=$_POST['bookname'];
$url = "http://example/star_avg.php?bookName=$bookname";
$json = file_get_contents($url);
$json_data = json_decode($json,TRUE);
echo 'data' + $json_data->results[0]->{'num'};
?>
My json data from other url is:
{"result":[{"avg":"3.9","num":"3"}]}
You see 0 printed because you're performing an addition + between the string data and a non-existent property. In PHP, to concatenate strings, do not use +; instead, use the dot . operator
In addition, because you're using true as the 2nd parameter to json_decode, what you get back is an array of arrays. Use the array notation [] rather than the object notation -> to access members.
$json_data = json_decode($json,TRUE);
$num = $json_data['result'][0]['num']; //<- array notation
echo 'data: '.$num; //prints data: 3
Live demo

get data from json array in php

I am having trouble accessing information in a json-Array that I retrieved using php's json_decode function.
the json-file looks as follows:
{"code":0,"message":"Okay","model":{"results":[{"message":"Okay","balance":0,"openPositions":[[],[]],"firstDepositDate":XXX,"currencySign":"€","email":"X.X#X.com","code":0}]},"result":"success"}
I used the following php code to get the contents:
$json = file_get_contents($json_url);
$data = json_decode($json,true);
echo '<pre>' . print_r($json, true) . '</pre>';
The result print_r displays looks just like what I expect and looks like the json.
However, I cannot figure out to access the variables. Whenever I try something like
$test = $json['model']['results']['balance'];
the script throws an error, which I can't identify. I already figured out if I access the $json variable like so:
$test = $json[n]; // returns the nth character, e.g. n = 0 $test = "{", n = 2 $test = "c"
The script also did not throw an error if I tried accessing the variable like so:
$test = $json['code']; // returns "{"
Can someone help me figure out how to navigate this array?
Thanks!
The results key is a true array, not an unordered map (key/value). Additionally, you should be accessing the decoded $data, not the $json string.
This should work for you:
$test = $data['model']['results'][0]['balance'];
This is what should have tipped you off:
{"results":[{"message"
^ ^
| |
| \-- Start of an array
|
\-- Start of an object
You recieve an error similar to Cannot use object of type stdClass as array in (...) right?
json_decode returns an object of the type stdClass which is the only object in php (as far as I know) which properties cannot be accessed like an array. You will have to access them as follows:
$json = '{"code":0,"message":"Okay","model":{"results":[{"message":"Okay","balance":0,"openPositions":[[],[]],"firstDepositDate":"XX","currencySign":"€","email":"X.X#X.com","code":0}]},"result":"success"}';
$obj = json_decode($json);
var_dump($obj->message); //works
var_dump($obj["message"]); //throws exception
There is an error in the JSON array. "firstDepositDate": XXX is not a valid value. Should be a string "XXX".
Also you are trying to the wrong variable. The decoded data should be a PHP array. In this case $data['code'] instead of $json['code']

How do I "trim" this JSON with PHP?

I have a JSON that's strangely formatted ...but it's the way I receive it. Because the arrays inside are huge, simply copying and pasting it takes a long time, so I'm wondering if there's a PHP way to do it.
The way I get it is like this:
{"count":459,"results":[{"title":"Something ....}],"params":{"limit..},"type":"Listing","pagination":{"..":5}}
But I want to get only the "results" array, basically the part of [{"title":"Something ....}]. How would I do that?
Do
$arr = json_decode(your_json, true);
If you ned it as JSON again, do
json_encode($arr['results']);
You can get to that part as follows:
$json = '{"count":459,"results":[{"title":"Something ...."}],"params":{"limit":".."},"type":"Listing","pagination":{"..":5}}';
$obj = json_decode($json);
echo $obj->results[0]->title;
Outputs:
Something ....
You have to decode your json. Be sure that the json is valid!
Your decoded json returns an object of type stdClass instead of an array!
See below the tested code:
$json = '{"count":459,"results":[{"title":"Something ...."}],"params":{"limit": "foo"},"type":"Listing","pagination":{"foo":5}}';
$decoded = json_decode($json);
So you can access array results from the object $decoded:
print_r($decoded->results);
But, in the array, there are objects, thus:
echo $decoded->results[0]->title; // Something ....

How to decode the following code in Json?

I'm trying to decode the following JSON using php json_decode function.
[{"total_count":17}]
I think the square brackets in output is preventing it. How do I get around that? I can't control the output because it is coming from Facebook FQL query:
https://api.facebook.com/method/fql.query?format=json&query=SELECT%20total_count%20FROM%20link_stat%20WHERE%20url=%22http://www.apple.com%22
PHP's json_decode returns an instance of stdClass by default.
For you, it's probably easier to deal with array. You can force PHP to return arrays, as a second parameter to json_decode:
$var = json_decode('[{"total_count":17}]', true);
After that, you can access the variable as $result[0]['total_count']
See this JS fiddle for an example of how to read it:
http://jsfiddle.net/8V4qP/1
It's basically the same code for PHP, except you need to pass true as your second argument to json_decode to tell php you want to use it as associative arrays instead of actual objects:
<?php
$result = json_decode('[{"total_count":17}]', true);
print $result[0]['total_count'];
?>
if you don't pass true, you would have to access it like this: $result[0]->total_count because it is an array containing an object, not an array containing an array.
$json = "[{\"total_count\":17}]";
$arr = Jason_decode($json);
foreach ($arr as $obj) {
echo $obj->total_count . "<br>";
}
Or use json_decode($json, true) if you want associative arrays instead of objects.

How to parse JSON string in php

I'm getting below JSON response:
[{"startDate":"2012-07-12 11:21:38 +0530","totalTime":0},{"startDate":"2012-07-11 11:27:33 +0530","totalTime":0},{"startDate":"2012-07-16 18:38:37 +0530","totalTime":0},{"startDate":"2012-07-17 14:18:32 +0530","totalTime":0}]
i want make array of start date and totalTime, i have used these two lines but it wont work $obj, please suggest..
$obj = json_decode($dateTimeArr);
$dateAr = $obj->{'startDate'};
As everyone said, and you did - use json_decode.
$dateArrays = json_decode($dateTimeArr, true); // decode JSON to associative array
foreach($dateArrays as $dateArr){
echo $dateArr['startDate'];
echo $dateArr['totalTime'];
}
In future, if you are unsure what type or structure of data is in the variable, do var_dump($var) and it will print type of variable and its content.
It is very easy:
$Arr = json_decode($JSON, true);
json_decode() will give you nested PHP types you can then descend to retrieve your data.
use json_decode($json_response,true) to convert json to Array
Guess what you are looking for is json_decode()
Check out http://php.net/manual/en/function.json-decode.php for the inner workings

Categories