Parsing JSON Results with PHP - Yahoo Search API
Asked Answered
S

1

6

I am able to retrieve results from yahoo with my API key, using the instructions found on the yahoo developers website. http://developer.yahoo.com/boss/search/boss_api_guide/codeexamples.html#

Code:

if ($_POST['query'])
{
$newline="<br />";
$query = urlencode("'{$_POST['query']}'");

require("OAuth.php");

$cc_key  = "key goes here";
$cc_secret = "secret goes here";
$url = "http://yboss.yahooapis.com/ysearch/web";
$args = array();
$args["q"] = "$query";
$args["format"] = "json";

$consumer = new OAuthConsumer($cc_key, $cc_secret);
$request = OAuthRequest::from_consumer_and_token($consumer, NULL,"GET", $url, $args);
$request->sign_request(new OAuthSignatureMethod_HMAC_SHA1(), $consumer, NULL);
$url = sprintf("%s?%s", $url, OAuthUtil::build_http_query($args));
$ch = curl_init();
$headers = array($request->to_header());
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_URL, $url);

curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); 
$rsp = curl_exec($ch);
$results = json_decode($rsp); 

print_r($results);

}

Using print_r($results) as shown above, I get results, such as the following (extract of first three results shown from searching for "elephant"):

PLEASE NOTE I HAVE CHANGED THE URLS TO "WWW" AS I REQUIRE AT LEAST 10 REPUTATION TO POST MORE THAN 2 LINKS.

stdClass Object ( [bossresponse] => stdClass Object ( [responsecode] => 200 [web] => stdClass Object ( [start] => 0 [count] => 50 [totalresults] => 36800000 [results] => Array ( [0] => stdClass Object ( [date] => [clickurl] => WWW [url] => WWW [dispurl] => en.wikipedia.org/wiki/Elephant [title] => Elephant - Wikipedia, the free encyclopedia [abstract] => Elephant trunks have multiple functions, including breathing, olfaction, ... One elephant has been observed to graze by kneeling on its front legs, ... ) [1] => stdClass Object ( [date] => [clickurl] => WWW [url] => WWW [dispurl] => www.defenders.org/elephant/basic-facts [title] => Elephant | Basic Facts About Elephants | Defenders of Wildlife [abstract] => Elephant. Basic Facts About Elephants More on Elephant: Threats to Elephants » More on Elephant: Basic Facts . Threats. What Defenders Is Doing to Help. What You Can ... ) [2] => stdClass Object ( [date] => [clickurl] => WWW [url] => WWW [dispurl] => kids.nationalgeographic.com/.../african-elephant [title] => African Elephant Facts and Pictures -- National Geographic Kids [abstract] => Kids' feature about elephants, with photographs, video, audio, fun facts, an e-mail postcard, and links to other animals. ) [3] => stdClass Object ( [date] => [clickurl] => WWW [url] => WWW [dispurl] => elephant.elehost.com/About_Elephants/about_elephants.htm [title] => About Elephants [abstract] => All about elephants on the Elephant Information Repository! This page includes a summary of elephant related facts to get you inducted in to the world of elephants. )

I have attempted to output the results, in a legible format, as follows:

Code Attempt 1:

foreach ($results->{ 'results' } as $item ) 
{

echo "<a href=\"{$item->{ 'url' }}\"><font color ='blue'>{$item->{ 'title' }}</font></a>".": "."$newline"."$newline".$item->{ 'abstract' }."\n\n";


}

I also tried the following, without success:

Code Attempt 2:

echo $results['results']['url'];
echo $results['results']['title'];
echo $results['results']['abstract'];

Any ideas on what to do?

Thanks.

Serum answered 1/7, 2013 at 9:16 Comment(2)
use "json_decode($json, true);" to get rid of the stdClass ObjectBrainstorm
The results look to me to be found under $results->bossresponse->web->resultsLicha
L
1

I've noticed you just copy-pasted the code from the documentation's code examples, but never mind that.

You're accessing the results array the wrong way:

foreach ($results->bossresponse->web->results as $result)
{
    //do stuff
    echo $result->title.'<br/>';
}

Or, as cptnk suggested:

$results = json_decode($rsp, true);
//force to assoc-array, which will allow array-access
foreach($results['bossresponse']['web']['results'] as $result)
{
    //$result is array here, but do the same stuff
    echo $result['title'].'<br/>';
}

Or, combine the two

foreach($results->bossresponse->web->results as $result)
{
    $result = (array) $result;//casts stdClass to array
    printf('<a href="%s">%s</a><br/>', $result['url'], $result['title']);
}
Licha answered 1/7, 2013 at 9:27 Comment(4)
Hey Elias, thanks for the help. I have been trying a few different methods for past hour,(ever since your answer). I am not having any luck. Based on the associative array suggestion I Tried: echo "<a href=\"{$result[2]->{ 'url' }}\"><font color ='blue'>{$result[2]->{ 'title' }}</font></a>".": "."$newline"."$newline".$result[2]->{ 'abstract' }."\n\n"; This only outputs the ":" for each result. This is really puzzling me, any more clues would be fantastic! :) Thanks.Serum
@Jenny: If you're passing true as second argument to json_decode, thre resulting array won't contain any objects, so $result[2]->{'url'} should be: $result[2]['url']. Also, are you accessing the results array correctly? It has to be accessed via $results['bossresponse']['web']['results'] if its an assoc array, or $response->bossresponse->web->results if it's an objectLicha
ah, I got it sorted now....I did is as an object, i.e. with '$response->bossresponse->web->results'... I did not need to say, for example: '$result[2]->url' just '$result->url'.. Thanks again! :)...how do you highlight code in a comment by the way?Serum
@Jenny, by enclosing it in back-ticks: this is code because I used ``Licha

© 2022 - 2024 — McMap. All rights reserved.