1

API を使用して、フォームに入力したユーザーが入力した単語をウィキペディアで検索しようとしています。そのため、フォームに「cat」と入力すると、API はウィキペディアで「cat」という単語を含むエントリを検索します。 "。動作するようになりましたが、次のメッセージが表示されます。

Warning: file_get_contents(http://en.wikipedia.org/w/api.php?action=opensearch&search=parrott): failed to open stream: HTTP request failed! HTTP/1.0 403 Forbidden in /var/www/html/flam1-api.php on line 22

おそらくユーザーエージェントが必要だと読んだのですが、正確に何をすべきかわかりません。これが私のコードです:

    echo "<h1>Which LOLcat are you? Results!</h1>";
    $visit_id = $_COOKIE['visit_id'];
    $all_my_variables = json_decode(file_get_contents("/var/www/html/data/$visit_id.json"));
    //var_dump($all_my_variables);
    $animal = $all_my_variables ->favoriteanimal;
    echo "When searching wikipedia entries on your favorite animal, which is a $animal, we got the results:<br>";
     $website = file_get_contents('http://en.wikipedia.org/w/api.php?action=opensearch&search='.urlencode($animal).'');

        echo $website[0];   

私は間違いなくこれに関する助けに感謝します!

4

2 に答える 2

3

ユーザー エージェントを設定する必要があります (おそらく のcurl代わりに拡張子を使用してfile_get_contents)。によって使用されるデフォルトのユーザー エージェントfile_get_contentsは、不正行為に関連付けられることが多いため、明示的にブロックされます。

于 2012-04-23T22:44:21.617 に答える
1

一部のサイトは、file_get_contents を使用してブロックします。今はテストする機会がありませんが、file_get_contents の代わりにこの関数を使用してみてください。

function get_url_contents($url){
        $crl = curl_init();
        $timeout = 5;
        curl_setopt ($crl, CURLOPT_URL,$url);
        curl_setopt ($crl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt ($crl, CURLOPT_CONNECTTIMEOUT, $timeout);
        $ret = curl_exec($crl);
        curl_close($crl);
        return $ret;
}
于 2012-04-23T22:45:46.567 に答える