3

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"}}}}

1 Answer 1

3

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

This does work. BUT I won't always know what 1332160 might be. How do I take into an account of a dynamic value there?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.