Reputation: 2706
Hi i googled i am not getting any cakephp heredoc. Please solve my problem
I want to use heredoc in CakePHP.
Code:
<?php
$qry = $this->Message->find("all");
$items = '';
$chatBoxes = array();
foreach ($qry as $chat) {
$items .=
<<<EOD
{
"s": "0",
"f": "{$chat['Message']['from']}",
"m": "{$chat['Message']['text']}"
},
EOD;
}
pr($items); exit;
?>
Above heredoc code not working getting following error message
Fatal Error
Error: syntax error, unexpected $end
File: E:\xampp\htdocs\2014\datingscanner\datingscanner\app\Controller\MessagesController.php
Line: 142
Notice: If you want to customize this error message, create app\View\Errors\fatal_error.ctp
Edit:
If i fetch the single value from databse it works fine.
$items .= $chat['Message']['from'];
Upvotes: 1
Views: 193
Reputation: 64526
This isn't a CakePHP specific problem. A valid heredoc must have no other characters before the closing identifier (you have whitespace), so it should look like:
<<<EOD
{
"s": "0",
"f": "{$chat['Message']['from']}",
"m": "{$chat['Message']['text']}"
},
EOD;
^ no whitespace or anything else before the close identifier
From the Manual:
Warning It is very important to note that the line with the closing identifier must contain no other characters, except a semicolon (;).
Side note: you appear to be manually building a JSON string. PHP has a built in functions to deal with JSON, so you can work with an array or object and have it transformed into JSON.
$items = array();
foreach ($qry as $chat) {
$items[] = array(
's' => '0',
'f' => $chat['Message']['from'],
'm' => $chat['Message']['text']
);
}
echo json_encode($items);
The above creates the same JSON that your current code creates. This way is better because json_encode()
will always produce valid JSON, and it will escape special characters that would otherwise break the JSON format.
Upvotes: 1