我已经成功地从Wikipedia返回了json,但没有任何运气来获取我在PHP中需要的值(试图在Drupal站点中做到这一点).
这是我正在使用的代码,您可以用$safeurl代替此值:
斯坎茨池塘州立公园
$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,我会看到以下包含我要执行的操作的文本,即“提取”值.我只是想不出要获取该段需要什么$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);
从那时起,您传递真实值,$parsed_json将成为一个数组.因此,删除真实标志.
并像访问…
$text = $parsed_json->query->pages->{1332160}->extract;
如果不知道1332160怎么办?
继续这样.
foreach($parsed_json->query->pages as $k)
{
echo $k->extract;
}
标签:wikipedia-api,json,php
来源: https://codeday.me/bug/20191122/2056195.html