1

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;
?>
John Verse
  • 29
  • 5

2 Answers2

0

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('/\{\$([^}]+)\}/i', function ($match) { 
            extract($GLOBALS);
            $parts = explode('->',$match[1]);
            $var = ${$parts[0]};
            for($i = 1; $i < count($parts); $i++) $var = $var->{$parts[$i]};
            return $var;
        }, $tplhtml);
Amirreza Noori
  • 1,456
  • 1
  • 6
  • 20
-1

Use eval function to evaluate a string as PHP code.

k1000
  • 78
  • 1
  • 5