<?php
include 'index.php';
if (@$_GET['search']) {
$url = "https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&titles=".ucwords($_GET['search'])."&redirects=true";
$url = str_replace('', '%20', $url);
if ($data = json_decode(@file_get_contents($url)))
{
foreach ($data->query->pages as $key => $value) {
$pageID = $key;
break;
}
$content = $data->query->pages->$pageID->extract;
echo $content;
}
}
?>
我上面有关于获取维基百科搜索结果内容的代码。但是问题是,如果我输入错误的关键字(例如“ makasia”)而不是“ malaysia”,则该关键字不会显示相关结果或任何内容,从而显示错误
“未定义的属性:stdClass :: $ extract”
答案 0 :(得分:0)
您的问题是,即使搜索失败,网站也会返回有效的JSON,因此对json_decode
的调用会返回一个对象(在布尔上下文中是真实的),从而导致您在自己的代码中执行代码if
语句,给您看到的错误。感谢@Tgr提供了API reference来指示缺少页面时返回数据的外观,此代码应该可以实现您想要的:
if (@$_GET['search']) {
$url = "https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&titles=".ucwords($_GET['search'])."&redirects=true";
$url = str_replace(' ', '%20', $url);
$data = json_decode(file_get_contents($url));
$found_data = false;
foreach ($data->query->pages as $page) {
if (property_exists($page, 'missing')) continue;
$found_data = true;
$content = $page->extract;
echo $content;
}
if (!$found_data) {
echo "No data for {$_GET['search']} found!";
}
}