I try to take from bing api related results and write script, who take me with print_r($value) this
Array
(
[0] => stdClass Object
(
[__metadata] => stdClass Object
(
[uri] => https://api.datamarket.azure.com/Data.ashx/Bing/Search/v1/RelatedSearch?Market='en-US'&Query='car'&$skip=0&$top=1
[type] => RelatedSearchResult
)
[ID] => 8bbe5043-f85b-41b3-b044-3649628fc5cf
[Title] => Cars Games
[BingUrl] => http://www.bing.com/search?q=Cars+Games
)
[1] => stdClass Object
(
[__metadata] => stdClass Object
(
[uri] => https://api.datamarket.azure.com/Data.ashx/Bing/Search/v1/RelatedSearch?Market='en-US'&Query='car'&$skip=1&$top=1
[type] => RelatedSearchResult
)
[ID] => b9df73ab-c410-4480-b172-2719643d1120
[Title] => Car Pictures
[BingUrl] => http://www.bing.com/search?q=Car+Pictures
)
)
How i can take [Title] and [BingUrl] from this array ? Thank you.
Use [] to access array elements and use -> to access object members.
In your case, it would be $arr[$index]->Title and $arr[$index]->BingUrl
Most APIs provide results in JSON format, so you may save yourself some headache by using json_decode($api_result, 1) to decode them as an array instead of an object.
If $value is array then you can use this code
foreach ($value as $item)
{
echo $item->Title;
echo $item->BingUrl
}
Related
I have a scenario where an API is returning multiple records inside object containing a numeric array like so;
stdClass Object
(
[Event] => Array
(
[0] => stdClass Object
(
[ID] => 111
[Name] => My First Event
[EventType] => stdClass Object
(
[ID] => 1
[Category] => Music
)
)
[1] => stdClass Object
(
[ID] => 222
[Name] => My Second Event
[EventType] => stdClass Object
(
[ID] => 2
[Category] => Sport
)
)
)
[Errors] => stdClass Object
(
[Result] => 0
[Message] =>
)
[RecordCount] => 2
)
I'm current using a foreach loop to iterate through the records. This works fine.
foreach($result->Event as $Event)
But there is a problem here I have a scenario where a single results is returned in the object like so;
stdClass Object
(
[Event] => stdClass Object
(
[ID] => 11
[Name] => My Only Event
[EventType] => stdClass Object
(
[ID] => 2
[Category] => Sport
)
)
[Errors] => stdClass Object
(
[Result] => 0
[Message] =>
)
[RecordCount] => 1
)
Notice there is no [0] array index for the single results.
What's the best way to overcome this keeping in mind that I have no control of the data returned by the API?
Check if Event is an array or an object
if( is_object( $result->Event ) )
{
// ...
}
else
{
foreach( // [....]
}
You may process the object or overwrite it with a 1 item array as suggested by Sam
Btw: very bad API design. I would complain....
The best workaround I have found is to add the single Event to an array with a zero index within the result object. This way the result object matches the same structure as a result containing multiple records.
if(!is_array($result->Event)){
$result->Event = array($result->Event);
}
I'm obtaining information from the Facebook Graph API that returns an array that contains several stdClass Objects. I can easily read the "top" level items such as $myGraph['id'] = 123111193 in the example below.
Can anyone show me how to get data from the stdClass Objects, for example School Name in the following example created with print_r()?
Array
(
[id] => 123111193
[education] => Array
(
[0] => stdClass Object
(
[school] => stdClass Object
(
[id] => 108177302537907
[name] => State College Area High School
)
[type] => High School
[year] => stdClass Object
(
[id] => 117615364954534
[name] => 1975
)
)
[1] => stdClass Object
(
[concentration] => Array
(
[0] => stdClass Object
(
[id] => 193334910691838
[name] => Individual and Family Studies
)
)
[school] => stdClass Object
(
[id] => 113618111985274
[name] => Pennsylvania State University
)
<?php
foreach($mainArray['education'] as $edObj)
{
echo $edObj->school->name;
}
Nothing fancy. If you have an std object called $foo and it has a $bar member, then you refer to it as $foo->bar. Example:
foreach ($mainArray["education"] as $value) {
echo $value->school->name;
}
I have a JSON array that I want to be able to drill down to a lower level and print just that value. The problem occurs when I reach a level that has is indacted as [0] (or [n]). For example I have the following output, and I want to just print the game key for the first league.
This is how I am trying to print it
HtmlSpecialChars(print_r($user->fantasy_content->users[0]->user[1]->games[0]->game[0]->game_key,1))
However I keep getting this error:
Cannot use object of type stdClass as array
When I do it incrementally it seems to fail on this command (so I assume I'm not index correctly):
$user->fantasy_content->users[0]
Here is the output:
stdClass Object
(
[fantasy_content] => stdClass Object
(
[xml:lang] => en-US
[yahoo:uri] => /fantasy/v2/users;use_login=1/games
[users] => stdClass Object
(
[0] => stdClass Object
(
[user] => Array
(
[0] => stdClass Object
(
[guid] => IYEZUHTVBYRLIB3OAQC5WRZPQY
)
[1] => stdClass Object
(
[games] => stdClass Object
(
[0] => stdClass Object
(
[game] => Array
(
[0] => stdClass Object
(
[game_key] => 147
[game_id] => 147
[name] => Baseball
[code] => mlb
[type] => full
[url] => http://baseball.fantasysports.yahoo.com/b1
[season] => 2006
)
)
)
[count] => 1
)
)
)
)
[count] => 1
)
[time] => 52.390813827515ms
[copyright] => Data provided by Yahoo! and STATS, LLC
[refresh_rate] => 60
)
)
For objects you must use the -> syntax and if the key/property name is a number or has other special characters, you will need to use the $object->{'0'} syntax.
The game_key can be retrieved using:
$user->fantasy_content->users->{'0'}->user[1]->games->{'0'}->game[0]->game_key;
You can convert a stdClass object to an array by casting it like so:
<?php
$array = (array) $myObject;
echo json_encode($array);
You can also cast inline:
<?php
echo json_encode((array) $object);
I have code for read XML SOAP 1.2 from web service.
Im using this: https://stackoverflow.com/a/18580428/2629513
I get this code below:
SimpleXMLElement Object
(
[OdkazyResponse] => SimpleXMLElement Object
(
[OdkazyResult] => SimpleXMLElement Object
(
[odkazy] => SimpleXMLElement Object
(
[odkaz] => Array
(
[0] => SimpleXMLElement Object
(
[#attributes] => Array
(
[kod_zbozi] => 31400001
[typ] => OBR1
[popis] => Oki ML 280 - foto
[url] => http://www.atcomp.cz/katalog/31400001/ML280.gif
)
)
[1] => SimpleXMLElement Object
(
[#attributes] => Array
(
[kod_zbozi] => EC376123GB
[typ] => OBR1
[popis] => Malý obrázek
[url] => http://www.atcomp.cz/katalog/EC376123GB/lq-680_-_maly.jpg
)
)
[2] => SimpleXMLElement Object
(
[#attributes] => Array
(
[kod_zbozi] => EC376123GB
[typ] => OBR2
[popis] => Velký obrázek
[url] => http://www.atcomp.cz/katalog/EC376123GB/lq-680_-_velky.jpg
)
)
And how I can read the [kod_zbozi], [typ], [popis], [url] attributes? I need to save it into my mysql database (this is not problem, the problem is read the data from this format XML). Thanks.
Well, the very first thing you might want to do is to convert that object into an array (to avoid naming problems)
You can use this function to do that:
function object2array($object) {
return json_decode(json_encode($object), true);
}
then something like this:
$data = object2array(simplexml_load_string('....'));
print_r($data); // Its regular array now, use it keys to access values, then simply insert them into db
I have got this result using json decode from an api call. but I dont know how to extract "VALUE" from this result..
$obj=json_decode($json_string);
print_r($obj);
stdClass Object ( [status] => OK [data] => stdClass Object ( [trends] => stdClass Object ( [rank] => Array ( [0] => stdClass Object ( [date] => 201011 [value] => 7196 ) ) ) [trends_low_sample] => [query_cost] => 1 [trends_frequency] => monthly ) )
I need only "7196" from this result. how do I do this??
Ah! Based on your updated code you're tring to get the value from PHP not Javascript? Personally I use json_decode($json_string,true); to get an associative array (json_decode), if you do that it should be accessible as:
echo $obj["data"]["trends"]["rank"][0]["value"];
As an object it's accessible as:
echo $obj->data->trends->rank[0]->value;