我希望能够使用 json 从维基百科中提取标题和描述。所以...维基百科不是我的问题,我是 json 的新手,想知道如何使用它。现在我知道有数百个教程,但我已经工作了几个小时,它只是不显示任何内容,这是我的代码:
<?php
$url="http://en.wikipedia.org/w/api.php?action=query&prop=extracts|info&exintro&titles=google&format=json&explaintext&redirects&inprop=url";
$json = file_get_contents($url);
$data = json_decode($json, TRUE);
$pageid = $data->query->pageids;
echo $data->query->pages->$pageid->title;
?>
只是为了更容易点击:
我知道我可能只是做错了一件小事,但这真的让我烦恼,而且代码......我习惯使用 xml,而且我几乎刚刚进行了切换,所以你能解释一下吗?对我和未来的访客来说,因为我很困惑......任何我没有说的你需要的东西,只需评论它,我相信我能得到它,提前谢谢!
$pageid
返回一个包含一个元素的数组。如果您只想获得第一个,您应该这样做:
$pageid = $data->query->pageids[0];
您可能收到此警告:
Array to string conversion
完整代码:
$url = 'http://en.wikipedia.org/w/api.php?action=query&prop=extracts|info&exintro&titles=google&format=json&explaintext&redirects&inprop=url&indexpageids';
$json = file_get_contents($url);
$data = json_decode($json);
$pageid = $data->query->pageids[0];
echo $data->query->pages->$pageid->title;
我会这样做。它支持同一个调用中有多个页面。
$url = "http://en.wikipedia.org/w/api.php?action=query&prop=extracts|info&exintro&titles=google&format=json&explaintext&redirects&inprop=url";
$json = file_get_contents($url);
$data = json_decode($json, TRUE);
$titles = array();
foreach ($data['query']['pages'] as $page) {
$titles[] = $page['title'];
}
var_dump($titles);
/* var_dump returns
array(1) {
[0]=>
string(6) "Google"
}
*/
这段代码是借助Wikipedia api从维基百科中提取标题和描述
<?php
$url = 'http://en.wikipedia.org/w/api.php?action=query&prop=extracts|info&exintro&titles=google&format=json&explaintext&redirects&inprop=url&indexpageids';
$json = file_get_contents($url);
$data = json_decode($json);
$pageid = $data->query->pageids[0];
$title = $data->query->pages->$pageid->title;
echo "<b>Title:</b> ".$title."<br>";
$string=$data->query->pages->$pageid->extract;
// to short the length of the string
$description = mb_strimwidth($string, 0, 322, '...');
// if you don't want to trim the text use this
/*
echo "<b>Description:</b> ".$string;
*/
echo "<b>Description:</b> ".$description;
?>