我正在尝试使用此PHP访问Stack Overflow上的最新评论列表:
<?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
有没有人对可能导致这种情况的原因有任何想法,以及如何解决这个问题?
答案 0 :(得分:5)
在这种情况下,应该从方法get
调用API。
如果您确实在此链接访问了API:https://api.stackexchange.com/2.1/comments?order=desc&sort=creation&site=stackoverflow
您将获得一个包含您想要的所有信息的精美JSON。
如果相反,你修改了post params:
$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);
答案 1 :(得分:-1)
因为错误说php_errormsg是你的问题。
在假定定义php_errormsg
之前,您必须确保跟踪错误。
在尝试获取php_errormsg
的值之前,您应该启用 track_errors 配置选项,例如:
<?php
function do_post_request($url, $data, $optional_headers = null)
{
error_reporting(E_ALL);
ini_set('track_errors', 1);
global $php_errormsg;
$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.ini配置文件中,您可以设置:
track_errors = On
重要提示:来自PHP website
虽然
$php_errormsg
是全局的,但它不是超全球。您必须在函数内使用全局关键字限定它。
<?php function checkErrormsg() {
global $php_errormsg;
@strpos();
return $php_errormsg; } ?>