Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/fortran/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP DOMDocument:替换父元素_Php_Dom_Domdocument - Fatal编程技术网

PHP DOMDocument:替换父元素

PHP DOMDocument:替换父元素,php,dom,domdocument,Php,Dom,Domdocument,考虑以下代码: <?php libxml_use_internal_errors(true); $exHTML = ' <div class="container"> <div class="para"> Some Text and <strong>HTML</strong>. </div> <div class="para">

考虑以下代码:

<?php

libxml_use_internal_errors(true);

$exHTML = '
    <div class="container">
        <div class="para">
            Some Text and <strong>HTML</strong>.
        </div>
        <div class="para">
            <div class="match-class another-one">Some text ...</div>
        </div>
        <div class="para">
            Some more Text and <strong>HTML</strong>.
        </div>
    </div>
    <div class="container">
        Another container whose content does not matter ...
    </div>
';

$dom = new DomDocument;
$dom->preserveWhiteSpace = false;

$dom->loadHTML($exHTML);

$finder = new DomXPath($dom);
$paragraphs = $finder->query("//div[@class='container'][1]//div[@class='para']");

foreach($paragraphs as $paragraph) {
    $elements = $finder->query("div[contains(@class, 'match-class another-one')]", $paragraph);

    foreach($elements as $element) {
        $newElement = $dom->createElement('p');
        $newElement->nodeValue = $element->nodeValue;
        $newElement->setAttribute('class', 'newclass');

        $paragraph->replaceChild($newElement, $element);
    }

    echo $dom->saveHTML($paragraph)."\n";
}
preserveWhiteSpace=false;
$dom->loadHTML($exHTML);
$finder=newdomxpath($dom);
$parations=$finder->query(//div[@class='container'][1]//div[@class='para']);
foreach($段落为$段落){
$elements=$finder->query(“div[contains(@class,'match class other one')”,$paragration);
foreach($elements作为$element){
$newElement=$dom->createElement('p');
$newElement->nodeValue=$element->nodeValue;
$newElement->setAttribute('class','newclass');
$paragration->replaceChild($newElement,$element);
}
echo$dom->saveHTML($段落)。“\n”;
}
最终结果应该是:

<p>
    Some Text and <strong>HTML</strong>.
</p>
<p class="newclass">
    Some text ...
</p>
<p>
    Some more Text and <strong>HTML</strong>.
</p>

一些文本和HTML

一些文字。。。

更多文本和HTML

如何修改和扩展代码以获得所需的结果?感谢您的帮助。 上面公布的代码导致以下结果:

<div class="para">
    Some Text and <strong>HTML</strong>.
</div>
<div class="para">
    <p class="newclass">Some text ...</p>
</div>
<div class="para">
    Some more Text and <strong>HTML</strong>.
</div>

一些文本和HTML

一些文本

更多文本和HTML