1

I have an array (mysql datafetch return) and a static string on my html page.

{result}

I defined a function to pass variables to my html page, but in case of the array it fails:

$this->page = str_replace("{".$ident."}", $var, $this->page);

$this->page is the complete content of the html page, fetched via file_get_contents(); any ideas?

$page is just a static html page:

<h1>Test</h1>
{var}
j0hn
  • 57
  • 7

1 Answers1

1

To solve this problem, you can convert the result array into a string and then replace the static variable on the HTML page. Here's how you can do this in PHP:

Convert the result array into a string, for example, using the implode() function.

Use the str_replace() function to replace the static variable on the HTML page with the string from the result array.

Here's an example code:

$page = file_get_contents('testCase.html');
$values = ["value1", "value2", "value3"];

$values_str = implode(", ", $values);

$ident = "var";
$page = str_replace('{' . $ident . '}', $values_str, $page);
echo $page;

testCase.html:

<h1>Test</h1>
{var}
bujals
  • 276
  • 1
  • 4
  • 16
  • 2
    Why would you prefer preg_replace in favor to str_replace in this simple case? preg_replace is an expensive operator, and it should be used very carefully, especially if you play the dangerous game of replacing content of a whole html page. – Stayko Dimitrov Jul 29 '16 at 21:39
  • 2
    Exactly thats what I currently do. But now how to insert more than one value into the placeholder? – j0hn Jul 30 '16 at 09:11