I have simple function in PHP that gives me
HTTP Error 500 (Internal Server Error):
When I comment it, the simple echo does get printed.
Here is the function:
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;
*/
}
I call it in the HTML file like this:
<?php
invokeAuthenticationServiceAPI();
?>
As you can see, I need to send it to rest api server. But it does fail only on the string to json formatting.
I have two questions:
You should check the web-server error log for the details of the error, but judging by the code you have posted, the problem is probably that there are spaces before the end of the heredoc JSON;
and the first time you use JSON
it should not be quoted.
You should use this:
$json = <<<JSON
{
"auth":
{
"username":"foo",
"password":"bar"
}
}
JSON; // no spaces before JSON;
instead of this:
$json = <<<"JSON"
{
"auth":
{
"username":"foo",
"password":"bar"
}
}
JSON;
Although personally I would generate an array or object in php and use json_encode
to generate the correct output.
Remove double quotes around JSON
and remove extra spaces which invalidate the PHP heredoc syntax
$json = <<<"JSON"
should be
$json = <<<JSON
Like
<?php
$str = <<<JSON
{
"auth":
{
"username":"foo",
"password":"bar"
}
}
JSON;
echo $str;
?>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.