I'm trying to create content from a template that has JSON object in it.
JSON data is fetched and saved but their properties and depth are unknown.
Textarea has text : {$obj->q} and some text {$keywordX}
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? Seems eval is not proper solution and thanks Amirreza Noori for pointing it out.
<form method="POST" name="varlines_form" action="">
<textarea name="varlines">
apple
101
space
</textarea>
<br />Tpl<br>
<textarea name="template">
{$obj->q} some text {$variableX}
</textarea><br />
<input type="submit" />
</form>
<?php
$variableX =" and EVEN more text ..";
$newcontent ="";
// if( $newcontent === 1 && (!empty($_POST)) && (isset($_POST['varlines']))){
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 = eval('return "' . $tplhtml . '";');
$html = preg_replace_callback('/\{\$obj->(.+)\}/i', function ($match) use($obj) { return $obj->{$match[1]}; }, $tplhtml);
// add results
$newcontent .= $html;
}
}
echo $newcontent;
?>