如何从php获取维基标题?

时间:2019-02-24 16:08:33

标签: php

如何使用api.php从维基百科获取标题?尝试:

$opts = array('https' =>
  array(
    'user_agent' => 'MyBot/1.0 (https://example.com/)'
  )
);
$context = stream_context_create($opts);

$url = 'https://en.wikipedia.org/w/api.php?action=query&titles=Your_Highness&prop=revisions&rvprop=content&rvsection=0';
dump(file_get_contents($url));

但是它总是返回false。

1 个答案:

答案 0 :(得分:1)

根据文档,您只需在调用API时传递format = json即可,因此您将以JSON获取响应,并且基于JSON对象,您可以访问响应中的任何值。

    <?php
       $url = 'https://en.wikipedia.org/w/api.php?action=query&titles=Your_Highness&prop=revisions&rvprop=content&rvsection=0&format=json';
       $context = stream_context_create(['http' => [
               'ignore_errors' => true,
       ]]);
       $body = file_get_contents($url, false, $context);
    ?>

此外,您也可以像这样使用curl。

$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
$response = curl_exec( $ch );

if ( $response === false) {
    $curl_result = curl_error( $ch );
    print_r( $curl_result );
} else {        
    print_r( json_decode($response) );
}
curl_close($ch);