phppostfatal-errorstackexchange-api

Getting an uncaught exception in PHP when trying to get data from POST API


I'm trying to access a list of most recent comments on Stack Overflow using this 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", "");
?>

However, when I run it, I get this error message:

$ 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

Does anyone have any ideas as to what might be causing this, and what one would do to fix it?


Solution

  • The API, in this situation, should be called from the method get.

    If you do visit the API at this link: https://api.stackexchange.com/2.1/comments?order=desc&sort=creation&site=stackoverflow
    You are presented with a nice JSON with all the information you want.

    If instead, you fix up the post params:

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

    You are shown this instead:

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

    Hopefully you know that you can simply just use file_get_contents to contact the API with the traditional get.

    $json = json_decode(file_get_contents("https://api.stackexchange.com/2.1/comments?order=desc&sort=creation&site=stackoverflow"), true);