Reputation: 30933
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:
Upvotes: 1
Views: 2731
Reputation: 46900
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;
?>
Upvotes: 1
Reputation: 1275
Upvotes: 0
Reputation: 91762
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.
Upvotes: 2