我在PHP中有一个简单的函数给我
HTTP错误500 (Internal Server Error):
当我注释它时,简单的echo会被打印出来。
函数如下:
error_reporting(E_ALL);
ini_set('display_errors', '1');
function invokeAuthenticationServiceAPI()
{
$json = <<<"JSON"
{
"auth":
{
"username":"foo",
"password":"bar"
}
}
JSON;
$data_string = json_decode($json);
echo $data_string;
/*
$ch = curl_init('https://apirestserverdemo/api');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
$result = curl_exec($ch);
echo $result;
*/
}
我在HTML文件中这样调用它:
<?php
invokeAuthenticationServiceAPI();
?>
如你所见,我需要将它发送到rest api服务器。但它确实只在字符串到json格式时失败。
我有两个问题:
- 也许我做了一些php不喜欢的事情。好的,但是我能得到某种错误信息而不是"错误500(内部服务器错误)"吗?
- 我做错了什么?
您应该检查web-server错误日志的错误细节,但根据您发布的代码判断,问题可能是在heredoc JSON;
和第一次使用JSON
结束之前有空格,它不应该被引用。
你应该这样写:
$json = <<<JSON
{
"auth":
{
"username":"foo",
"password":"bar"
}
}
JSON; // no spaces before JSON;
而不是:
$json = <<<"JSON"
{
"auth":
{
"username":"foo",
"password":"bar"
}
}
JSON;
虽然我个人会在php中生成一个数组或对象,并使用json_encode
来生成正确的输出。
删除JSON
周围的双引号,并删除使PHP heredoc语法无效的额外空格
$json = <<<"JSON"
应该$json = <<<JSON
<?php
$str = <<<JSON
{
"auth":
{
"username":"foo",
"password":"bar"
}
}
JSON;
echo $str;
?>
- 如果你有一个500的内部服务器错误,你几乎肯定有一个致命的错误在PHP。根据您的代码,您可能会在错误日志中发现错误,或者您可能必须使用xdebug来调试代码。
- JSON不需要引号。除此之外,您的代码不会立即出错。但是你应该使用json_encode生成JSON。