0

I have a problem on my script it duplicates the output from the .html file. here is my code below.

php:

<?php
$html = file_exists('try.html') ? file_get_contents('try.html') : die('unable to open the file');

$data['test1'] = 'WRITE 1';

$data['test2'] = 'WRITE 2';

foreach ($data as $search => $value)
{
    if(preg_match_all('#(<([a-zA-Z]+)[^>]*id=")(.*'.$search.')("[^>]*>)([^<]*?)(</\\2>)#ism', $html, $matches, PREG_SET_ORDER))
    {
        foreach($matches as $match) 
        {
            $xhtml = str_replace($match[5],$value,$html);
            echo $xhtml;
        }
    }
}
?>

html:

<html>
<head>
<title>TRY</title>
</head>
<body>
<div id="test1">A</div>
<div id="test2">B</div>
</body>
</html>

OUTPUT:

WRITE 1
B

A
WRITE 2

it duplicates the output.

DESIRED OUTPUT:

WRITE 1
WRITE 2

1 Answer 1

1

You have this as your foreach loop:

foreach($matches as $match) 
{
    $xhtml = str_replace($match[5],$value,$html);
    echo $xhtml;
}

The echo is inside the loop, so you do one replacement each time, then echo $xhtml each time. What you want is this:

<?php
$html = file_exists('try.html') ? file_get_contents('try.html') : die('unable to open the file');

$data['test1'] = 'WRITE 1';

$data['test2'] = 'WRITE 2';

foreach ($data as $search => $value)
{
    if(preg_match_all('#(<([a-zA-Z]+)[^>]*id=")(.*'.$search.')("[^>]*>)([^<]*?)(</\\2>)#ism', $html, $matches, PREG_SET_ORDER))
    {
        foreach($matches as $match) 
        {
            $html = str_replace($match[5],$value,$html);
        }
    }
}
echo $html;
?>
Sign up to request clarification or add additional context in comments.

1 Comment

quite confussing about the variable $xhtml thats why if I used it will only output a 1 variable value so you used $html to override it. thank you so much. I was just confused on variables.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.