-2

この PHP を使用して、スタック オーバーフローに関する最新のコメントのリストにアクセスしようとしています。

<?php
    function do_post_request($url, $data, $optional_headers = null)
    {
      $params = array('http' => array(
                  'method' => 'POST',
                  'content' => $data
                ));
      if ($optional_headers !== null) {
        $params['http']['header'] = $optional_headers;
      }
      $ctx = stream_context_create($params);
      $fp = @fopen($url, 'rb', false, $ctx);
      if (!$fp) {
        throw new Exception("Problem with $url, $php_errormsg");
      }
      $response = @stream_get_contents($fp);
      if ($response === false) {
        throw new Exception("Problem reading data from $url, $php_errormsg");
      }
      return $response;
    }
    echo do_post_request("https://api.stackexchange.com/2.1/comments?order=desc&sort=creation&site=stackoverflow", "");
?>

ただし、実行すると、次のエラー メッセージが表示されます。

$ php index.php 

PHP Notice:  Undefined variable: php_errormsg in /var/www/secomments/index.php on line 14
PHP Fatal error:  Uncaught exception 'Exception' with message 'Problem with https://api.stackexchange.com/2.1/comments?order=desc&sort=creation&site=stackoverflow, ' in /var/www/secomments/index.php:14
Stack trace:
#0 /var/www/secomments/index.php(22): do_post_request('https://api.sta...', '')
#1 {main}
  thrown in /var/www/secomments/index.php on line 14

これを引き起こしている可能性のあるものと、それを修正するために何をするかについて、誰か考えがありますか?

4

2 に答える 2

5

この場合、API はメソッドから呼び出す必要がありますget

このリンクの API にアクセスするhttps://api.stackexchange.com/2.1/comments?order=desc&sort=creation&site=stackoverflow
と、必要なすべての情報が含まれた適切な JSON が表示されます。

代わりに、投稿パラメーターを修正する場合:

$params = array('http' => array(
    'method' => 'POST',
    'content' => $data,
    'header' => 'Content-Length: ' . strlen($data)
));

代わりにこれが表示されます。

{"error_id":404,"error_name":"no_method","error_message":"this method cannot be called this way"}

file_get_contentsうまくいけば、従来の get を使用して API にアクセスするだけでよいことがわかります。

$json = json_decode(file_get_contents("https://api.stackexchange.com/2.1/comments?order=desc&sort=creation&site=stackoverflow"), true);
于 2013-10-04T03:31:15.483 に答える