extract specific data from json array using php curl [duplicate] - php

this is what i get as a string from a feed finder url (JSON Encoded):
{
"updated": 1265787927,
"id": "http://www.google.com/reader/api/0/feed-finder?q\u003dhttp://itcapsule.blogspot.com/\u0026output\u003djson",
"title": "Feed results for \"http://itcapsule.blogspot.com/\"",
"self": [{
"href": "http://www.google.com/reader/api/0/feed-finder?q\u003dhttp://itcapsule.blogspot.com/\u0026output\u003djson"
}],
"feed": [{
"href": "http://itcapsule.blogspot.com/feeds/posts/default"
}]
}
How can i decode it using json_decode() function in php and get the last array element ("feed") ? i tried it with the following code but no luck
$json = file_get_contents("http://www.google.com/reader/api/0/feed-finder?q=http://itcapsule.blogspot.com/&output=json");
$ar = (array)(json_decode($json,true));
print_r $ar;
Please help ..

$array = json_decode($json, true);
$feed = $array['feed'];
Note that json_decode() already returns an array when you call it with true as second parameter.
Update:
As the value of feed in JSON
"feed":[{"href":"http://itcapsule.blogspot.com/feeds/posts/default"}]
is an array of objects, the content of $array['feed'] is:
Array
(
[0] => Array
(
[href] => http://itcapsule.blogspot.com/feeds/posts/default
)
)
To get the URL you have to access the array with $array['feed'][0]['href'] or $feed[0]['href'].
But this is basic handling of arrays. Maybe the Arrays documentation helps you.

Related

Python to PHP | String to Multidimensional Json Object To Array

I have a python script which returns an object as string. I call this python script with php and then print out the result with var_dump(json_decode($result)) and get this (this it the right object I want so my python code works properly I guess):
string(467) "{"userData": {"geburtsdatum": "PMS_2018-01-01", "anrede": "PMS_Herr", "ID": "1", "nachname": "PMS_Nachname1", "Test": {"tel": "PMS_Tel1", "postalOptIn": 0, "postal": "S3_Postal1", "email": "PMS_EMail1"}, "vorname": "PMS_Vorname1" }} "
So as you can see its a string on php side.
But how can I convert it to an object now and the create a multidimensional array from it in php?
If you need more information pls ask Ill add it.
I tried:
json_decode($result, true);
json_decode($result);
$response = (array) $result;
all I get is an Array with 1 Index and the whole Object as Value in it.
The Object gets generated like this on python side:
for message in consumer:
if message.key == str.encode(sys.argv[1]):
returnValue = message.value #this here is an byte obj from external system
consumer.close()
print(returnValue.decode("latin-1"))
Edit 2 and Solution
After long search I found out that the service I'm using (3d Party) returns the result from the python script with json_encode(). I removed that and now this code works:
$array = json_decode($response, TRUE);
return var_dump($array);
Since it is a string you can decode it like this:
$string = '{"userData": {"geburtsdatum": "PMS_2018-01-01", "anrede": "PMS_Herr", "ID": "1", "nachname": "PMS_Nachname1", "Test": {"tel": "PMS_Tel1", "postalOptIn": 0, "postal": "S3_Postal1", "email": "PMS_EMail1"}, "vorname": "PMS_Vorname1" }}';
print_r(json_decode($string, true));
Which returns an array:
Array
(
[userData] => Array
(
[geburtsdatum] => PMS_2018-01-01
[anrede] => PMS_Herr
[ID] => 1
[nachname] => PMS_Nachname1
[Test] => Array
(
[tel] => PMS_Tel1
[postalOptIn] => 0
[postal] => S3_Postal1
[email] => PMS_EMail1
)
[vorname] => PMS_Vorname1
)
)

I'm trying to decode json array to php but it's returning a blank page

I'm trying to decode json array to php array using json_decode, but it's displaying a blank page
Here's the json array
[["id":"2","name":"Sam Nju","photo":"1510074080885.jpg","qty":"10","price":"10000.00"],["id":"3","name":"Daniel","photo":"1510074047056.jpg","qty":"0","price":"40000.00"]]
Here's the code to decode json
$json = file_get_contents('http://localhost/example/index.php/destinations/json');
$data = json_decode($json,true);
$names = $data['result'];
echo "<pre>";
echo $names;
print_r($names);
Thanks
For obtaining proper JSON using json_decode() and json_encode() follow these guidelines:
json_decode() :
This function only works with UTF-8 encoded strings.
Returns the value encoded in json in appropriate PHP type. Values true, false and null are returned as TRUE, FALSE and NULL respectively. NULL is returned if the json cannot be decoded or if the encoded data is deeper than the recursion limit.
The key and value must be enclosed in double quotes single quotes are not valid.
Your JSON:
[["id":"2","name":"Sam Nju","photo":"1510074080885.jpg","qty":"10","price":"10000.00"],["id":"3","name":"Daniel","photo":"1510074047056.jpg","qty":"0","price":"40000.00"]]
apears to be invalid. Arrays use [] while objects use {}.
This is an example of how a proper PHP array structure would look like prior to doing json_encode() (before sending):
// array structure in PHP to get proper JSON
Array ( [0] => Array ( [id] => 2 [name] => Sam Nju [photo] => 1510074080885.jpg [qty] => 10 [price] => 10000.00 ) [1] => Array ( [id] => 3 [name] => Daniel [photo] => 1510074047056.jpg [qty] => 0 [price] => 40000.00 ) )
which was obtained using the following:
json_decode('[{"id":"2","name":"Sam Nju","photo":"1510074080885.jpg","qty":"10","price":"10000.00"},{"id":"3","name":"Daniel","photo":"1510074047056.jpg","qty":"0","price":"40000.00"}]', true)
which would mean doing this:
$myArray = array();
$firstPerson = array();
$secondPerson = array();
$firstPerson['id'] = 2;
$firstPerson['name'] = "Sam Nju";
// ...
$secondPerson['id'] = 3;
$firstPerson['name'] = "Daniel";
// ...
array_push($myArray, $firstPerson);
array_push($myArray, $secondPerson);
// or $myArray[0] = $firstPerson; and $myArray[1] = $secondPerson;
While valid JSON would look like this:
{{"id":"2","name":"Sam Nju","photo":"1510074080885.jpg","qty":"10","price":"10000.00"},{"id":"3","name":"Daniel","photo":"1510074047056.jpg","qty":"0","price":"40000.00"}}
If you are getting the data from a database you might want to use something like this:
$result = mysqli_query($con, "SELECT .... // database query, $con is connection variable
$myArray = array();
while($row = mysqli_fetch_array($result))
{
$tempArray = array();
$tempArray['id'] = $row[0];
$tempArray['name'] = $row[1];
$tempArray['photo'] = $row[2];
// ...
array_push($myArray, $tempArray);
}
// use print_r($myArray); to test it out.
Although your code looks correct, your JSON data is invalid. Objects are enclosed by {}, not []. Replace the JSON with this, and it should work.
[
{
"id": "2",
"name": "Sam Nju",
"photo": "1510074080885.jpg",
"qty": "10",
"price": "10000.00"
},
{
"id": "3",
"name": "Daniel",
"photo": "1510074047056.jpg",
"qty": "0",
"price": "40000.00"
}
]
Also above answer already mentioned it:
Your JSON is invalid. You can check this e.g. with an JSON linter like https://jsonlint.com/
Plus, you're referencing names with $names = $data['result'];. However, in your provided JSON there is no array (or better object), with key "result".
You may look up your PHP's error log file to understand where the problem lies.

Json, PHP, and sessions

I would like to print a value from the following JSON in PHP. How would I access a specific value? Also this array is stored in a session call forminfo. So I need to access the session then the specific value of FirstName for example.
Array (
[forminfo] => stdClass Object (
[GetProspectAsJSONResult] => [
{
"ProspectId": xxxxx,
"Keycode": "Test123",
"FirstName": "Test",
"LastName": "Test",
"Company": "Test",
"Email": null
}
]
)
)
Thanks!
you should use json_decode on object which decodes it and returns an array. then you could for example access Firstname with decodedArray['FirstName']

php json decode - get a value

I'm trying to extract a specific value from json content . Here it is link with the json code http://www.ebayclassifieds.com/m/AreaSearch?jsoncallback=json&lat=41.1131514&lng=-74.0437521 As you may see the the code displayed is
json({items:[{url:"http://fairfield.ebayclassifieds.com/",name:"Fairfield"},{url:"http://newyork.ebayclassifieds.com/",name:"New York City"}],error:null});
I need to extract the first url which in this case is "http://fairfield.ebayclassifieds.com/" and its name value which is "Fairfield" , I could do it with regex but I would prefer to use json_decode. Unfortunately when I try to decode it doesn't work
$json = getContent("http://www.ebayclassifieds.com/m/AreaSearch?jsoncallback=json&lat=41.1131514&lng=-74.0437521");
$test = json_decode($json, true);
As danp already said, the returned JSON is enclosed in a function call (specified by jsoncallback=json). You cannot get rid of this totally but, just using AreaSearch?jsoncallback=&lat=41.1131514&lng=-74.0437521 removes at least the json at the beginning of the string and you can get rid of the brackets by:
$json = trim(trim($json), "();");
with gives:
{items:[{url:"http://fairfield.ebayclassifieds.com/",name:"Fairfield"},{url:"http://newyork.ebayclassifieds.com/",name:"New York City"}],error:null}
Unfortunately, the JSON string is not valid. The keys (items, url, ...) have to be enclosed in quotes ". You can easily check that you get a syntax error with json_last_error() (error code 4, JSON_ERROR_SYNTAX).
Update:
According to this question: Invalid JSON parsing using PHP , you can make the JSON string valid with:
$json = preg_replace('/(\w+):/i', '"\1":', $json);
This encloses the keys in quotes.
If the string would be valid, then you could generate an array via:
$a = json_decode($json, true);
which would give you:
Array
(
[items] => Array
(
[0] => Array
(
[url] => http://fairfield.ebayclassifieds.com/
[name] => Fairfield
)
[1] => Array
(
[url] => http://newyork.ebayclassifieds.com/
[name] => New York City
)
)
[error] =>
)
So you could get the first URL and name via $a['items'][0]['url'] and $a['items'][0]['name'] resp.
But I repeat, the JSON you get as response is not valid and you cannot parse it with json_decode() in its original form.
Its not valid JSON. The keys should be wrapped inside quotes.
You can validate your json using the excellent JSON Lint site.
This is a valid version of the data returned:
{
"items": [
{
"url": "http://fairfield.ebayclassifieds.com/",
"name": "Fairfield"
},
{
"url": "http://newyork.ebayclassifieds.com/",
"name": "New York City"
}
],
"error": "null"
}

how to decode this JSON string?

this is what i get as a string from a feed finder url (JSON Encoded):
{
"updated": 1265787927,
"id": "http://www.google.com/reader/api/0/feed-finder?q\u003dhttp://itcapsule.blogspot.com/\u0026output\u003djson",
"title": "Feed results for \"http://itcapsule.blogspot.com/\"",
"self": [{
"href": "http://www.google.com/reader/api/0/feed-finder?q\u003dhttp://itcapsule.blogspot.com/\u0026output\u003djson"
}],
"feed": [{
"href": "http://itcapsule.blogspot.com/feeds/posts/default"
}]
}
How can i decode it using json_decode() function in php and get the last array element ("feed") ? i tried it with the following code but no luck
$json = file_get_contents("http://www.google.com/reader/api/0/feed-finder?q=http://itcapsule.blogspot.com/&output=json");
$ar = (array)(json_decode($json,true));
print_r $ar;
Please help ..
$array = json_decode($json, true);
$feed = $array['feed'];
Note that json_decode() already returns an array when you call it with true as second parameter.
Update:
As the value of feed in JSON
"feed":[{"href":"http://itcapsule.blogspot.com/feeds/posts/default"}]
is an array of objects, the content of $array['feed'] is:
Array
(
[0] => Array
(
[href] => http://itcapsule.blogspot.com/feeds/posts/default
)
)
To get the URL you have to access the array with $array['feed'][0]['href'] or $feed[0]['href'].
But this is basic handling of arrays. Maybe the Arrays documentation helps you.

Categories