用PHP解析维基百科API json


Parsing Wikipedia API json in PHP

我成功地从维基百科返回json,但我没有任何运气在PHP中抓取我需要的值(试图在Drupal站点中这样做)。

下面是我使用的代码,你可以用$safeurl替换这个值:Squantz % 20池塘% 20国家公园% 20

<?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;
?>

如果我在我的HTML中打印$json_string,我看到下面的文本,其中包含了我要做的,"extract"值。我只是不明白$text需要是什么来抓取那个段落。

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

您需要将json_decode更改为

$parsed_json = json_decode($json_string);

由于传递true, $parsed_json将成为一个数组。所以去掉true标志

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

如果1332160是未知的呢?

按此进行…

foreach($parsed_json->query->pages as $k)
{
    echo $k->extract;
}