Home>

This is a new issue with the content of the question in the php tag DOM tag replacement .

<? php ob_start ('buffer_page');?>
<html>
<body>
<div>hogehoge</div>
<div>hogehoge</div>
<div>hogehoge</div>
<div>hogehoge</div>
<div>hogehoge</div>
<div>hogehoge</div>
<div>hogehoge</div>
<div>hogehoge</div>
<div>hogehoge</div>
<div>hogehoge</div>
<div>hogehoge</div>
<div>hogehoge</div>
<div>hogehoge</div>
<div>hogehoge</div>
<div>hogehoge</div>
<div>hogehoge</div>
<div>hogehoge</div>
<div>hogehoge</div>
<div>hogehoge</div>
<div>hogehoge</div>
</body>
</html>
<? php ob_end_flush ();?>
function buffer_page ($content)
{
    $buffer = new bufferPage ();
    $content = $buffer->formatHtml ($content);
    return $content;
}
class bufferPage
{
    public function formatHtml ($content)
    {
        $dom = new DOMDocument ();
        $dom->loadHTML ($content);
        $divs = $dom->getElementsByTagName ('div');
        foreach ($divs as $div):
            if ($div->hasAttribute ('class')&&preg_match ('/ target-class/i', $div->getAttribute ('class'))) (
                $new_p = $dom->createElement ('p');
                // copy all attributes
                foreach ($div->attributes as $attr) {
                    $new_p->setAttribute ($attr->nodeName, $attr->nodeValue);
                }
                $new_p_content = $div->nodeValue;
                $new_p->nodeValue = "<span class = \" target-class-inner \ ">{$new_p_content}</span>";
                $div->parentNode->replaceChild ($new_p, $div);
            }
        endforeach;
        return mb_convert_encoding ($dom->saveHTML (), 'UTF-8', 'HTML-ENTITIES');
    }
}


Html is replaced with

<p><span>hogehoge</span></p>
<div>hogehoge</div>
<p><span>hogehoge</span></p>
<div>hogehoge</div>
<p><span>hogehoge</span></p>
<div>hogehoge</div>
<p><span>hogehoge</span></p>
<div>hogehoge</div>
<p><span>hogehoge</span></p>
<div>hogehoge</div>
<p><span>hogehoge</span></p>
<div>hogehoge</div>
<p><span>hogehoge</span></p>
<div>hogehoge</div>
<p><span>hogehoge</span></p>
<div>hogehoge</div>
<p><span>hogehoge</span></p>
<div>hogehoge</div>
<p><span>hogehoge</span></p>
<div>hogehoge</div>


And one will be skipped.
I ’m sorry for the inconvenience.

php
  • Answer # 1

    As with JavaScript DOM, the list returned bygetElementsByTagNameisdynamicand reflects the state of the DOM.

    Therefore, if you rewrite the original DOM while referring toforeach, "Refer to 0th and replace with<p>" → " Even though it is intended to refer to the first one, the first one (0th after rewriting) is left unattended even if it is shifted by rewriting. "

    Copy it to a simple array and replace it, or process itafterwith a normalforstatement (even if the last one is reduced) Does not affect the subscripts of the rest, etc.).

  • Answer # 2

    for ($i = $divs->length-1;$i>= 0;$i-) {
      $div = $divs->item ($i);
      ...
    }

Related articles