I'm successfully returning json from Wikipedia but am not having any luck grabbing the value I need in PHP (trying to do this in a Drupal site).

Here is the code I'm using, you can substitute $safeurl for this value: Squantz%20Pond%20State%20Park

<?php 
    $safeurl = str_replace(' ', '%20', $title); 
    $json_string = file_get_contents("http://en.wikipedia.org/w/api.php?action=query&prop=extracts&format=json&exintro=&titles=" . $safeurl); 
    $parsed_json = json_decode($json_string, true); 
    $text = $parsed_json->{'extract'}; 
    print "What I need:" . $text;
?>

If I print $json_string out in my HTML I see the following text which contains what I'm going after, the "extract" value. I just can't figure out what $text needs to be to grab that paragraph.

{"query":{"pages":{"1332160":{"pageid":1332160,"ns":0,"title":"Squantz Pond State     Park","extract":"Squantz Pond State Park is a state park located 10 miles (16\u00a0km) north of Danbury in the town of New Fairfield, Connecticut. The park offers opportunities for swimming, fishing, hiking and boating.\n"}}}}
有帮助吗?

解决方案

You need to change your json_decode to

$parsed_json = json_decode($json_string);

Since, you pass the true the $parsed_json will become an array. So remove the true flag.

and access it like ...

$text = $parsed_json->query->pages->{1332160}->extract;

What if 1332160 is not known ?

Proceed like this..

foreach($parsed_json->query->pages as $k)
{
    echo $k->extract;
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top