维基百科API不会为某些查询返回任何内容

时间:2013-09-02 03:16:58

标签: php javascript html api wikipedia

HTML

<html>
<head>
</head>
<form action="check2.php" method="POST">
    Search <input type="text" name="search" />
    <input type="submit" name="searchbtn" value="search" />
</form>
</body>
</html>

PHP

<?php
    $string = $_POST['search'];
    $convert = rawurlencode($string);
    $url = 'http://en.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&format=xml&redirects&titles='.$convert;
    if($_POST['search'] != '' || $_POST['search'] != null) {
        $ch = curl_init($url);
        curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
        $c = curl_exec($ch);
        echo $c;
    } else {

    }
?>

如果我搜索(示例)“纽约”,则返回XML,但如果我搜索“新加坡动物园”,则返回任何内容

1 个答案:

答案 0 :(得分:1)

首先,你是supposed to set a User-Agent。其次,这不是搜索,而是以特定标题导出页面;你正在寻找action=opensearch

https://en.wikipedia.org/w/api.php?action=opensearch&search=api&limit=1&namespace=0&search=Singapore_Zoo&utf8=true给出:

["Singapore_Zoo",["Singapore Zoo"],["The Singapore Zoo (Chinese: 新加坡动物园; pinyin: Xīnjiāpō Dòngwùyuán; Malay: 'Taman Haiwan Singapura'; Tamil: சிங்கப்பூர் விலங்குக் காட்சிச்சாலை), formerly known as the Singapore Zoological Gardens and commonly known locally as the Mandai Zoo, occupies 28 hectares (69 acres) on the margins of Upper Seletar Reservoir within Singapore's heavily forested central catchment area."],["https://en.wikipedia.org/wiki/Singapore_Zoo"]]