I'm trying to create content from a template that has JSON object in it.
JSON data is fetched and saved
Textarea has text : {$obj->q} and some text
The value of the text area contains the name of the object variable in form of text.
How to save the value of $obj->q inside the $newcontent variable?
<form method="POST" name="varlines_form" action="">
<textarea name="varlines">
apple
101
space
</textarea>
<br />Tpl<br>
<textarea name="template">
{$obj->q} and some text ...
</textarea><br />
<input type="submit" />
</form>
<?php
$newcontent ="";
if((!empty($_POST)) && (isset($_POST['varlines']))){
$txtstring = trim($_POST['varlines']);
$kws = preg_split('/[\n\r] /', $txtstring);
$kws = array_filter($kws, 'trim'); // remove any extra \r characters left behind
$tplhtml = $_POST['template'];
// Loop through each keywords in array (keyword/key phrase)
foreach($kws as $kword){
$q = $kword;
// test json url
$tmp = "http://echo.jsontest.com/key/value/q/$q";
$json = file_get_contents($tmp);
$obj = json_decode($json);
echo "inside loop: ";
echo $obj->q;
echo " <br />";
// get template
// htmltpl
// identify {tags}
// replace {tags} with $result[obj] values
// variable of variables
$html = $$tplhtml;
// add results
$newcontent .= $html;
}
}
echo $newcontent;
?>
CodePudding user response:
Using eval
is very unsafe way to solve this problem:
When is eval evil in php?
One solution is using preg_replace_callback
function and find your desired format with regex and replace it with custom function.
preg_replace_callback
function perform a regular expression search and replace using a callback.
https://www.php.net/manual/en/function.preg-replace-callback.php
Just need to replace line $html = $$tplhtml;
with following line:
$html = preg_replace_callback('/\{\$obj->(. )\}/i', function ($match) use($obj) { return $obj->{$match[1]}; }, $tplhtml);
CodePudding user response:
Use eval function to evaluate a string as PHP code.