I'm trying to parse a blade template string into php format and use eval() to evaluate string as php code
$array = [
'foo' => 'bar',
'bar' => 'foo'
];
$content = '@foreach($array as $value){{$value}}@endforeach';
$blade = Blade::compileString($content);
$php = eval($blade);
This is my code for testing so far and it throws exception
ParseError: syntax error, unexpected '<', expecting end of file
value of $blade after compileString()
<?php $__currentLoopData = $array; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $value): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?><?php echo e($value); ?><?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
What causes this error? Is eval() not compatible with the way compileString() is parsing blade into php?
As stated in the manual:
The code must not be wrapped in opening and closing PHP tags, i.e.
'echo "Hi!";'
must be passed instead of'<?php echo "Hi!"; ?>'
. It is still possible to leave and re-enter PHP mode though using the appropriate PHP tags, e.g.'echo "In PHP mode!"; ?>In HTML mode!<?php echo "Back in PHP mode!";'
.
Your blade is wrapped in <?php
tags, and the compilation fails. Remove the enclosing PHP tags, but leave the interstitial tags.