如何使用XPath和DOM替换php中的节点/元素?

Har*_*ldo 9 php xpath dom

说我有以下HTML

$html = '
<div class="website">
    <div>
        <div id="old_div">
            <p>some text</p>
            <p>some text</p>
            <p>some text</p>
            <p>some text</p>
            <div class="a class">
                <p>some text</p>
                <p>some text</p>
            </div>
        </div>
        <div id="another_div"></div>
    </div>
</div>
';
Run Code Online (Sandbox Code Playgroud)

我想#old_div用以下内容替换:

$replacement = '<div id="new_div">this is new</div>';
Run Code Online (Sandbox Code Playgroud)

给出最终结果:

$html = '
<div class="website">
        <div>
            <div id="new_div">this is new</div>
            <div id="another_div"></div>
        </div>
    </div>
';
Run Code Online (Sandbox Code Playgroud)

使用PHP执行此操作是否有简单的剪切和粘贴功能?


最后的工作代码归功于戈登的所有帮助:

<?php

$html = <<< HTML
<div class="website">
    <div>
        <div id="old_div">
            <p>some text</p>
            <p>some text</p>
            <p>some text</p>
            <p>some text</p>
            <div class="a class">
                <p>some text</p>
                <p>some text</p>
            </div>
        </div>
        <div id="another_div"></div>
    </div>
</div>
HTML;

$dom = new DOMDocument;
$dom->loadXml($html); // use loadHTML if it's invalid XHTML

//create replacement
$replacement  = $dom->createDocumentFragment();
$replacement  ->appendXML('<div id="new_div">this is new</div>');

//make replacement
$xp = new DOMXPath($dom);
$oldNode = $xp->query('//div[@id="old_div"]')->item(0);
$oldNode->parentNode->replaceChild($replacement  , $oldNode);
//save html output
$new_html = $dom->saveXml($dom->documentElement);

echo $new_html;

?>
Run Code Online (Sandbox Code Playgroud)

Gor*_*don 10

由于链接副本中的答案并不全面,我将举例说明:

$dom = new DOMDocument;
$dom->loadXml($html); // use loadHTML if its invalid (X)HTML

// create the new element
$newNode = $dom->createElement('div', 'this is new');
$newNode->setAttribute('id', 'new_div');

// fetch and replace the old element
$oldNode = $dom->getElementById('old_div');
$oldNode->parentNode->replaceChild($newNode, $oldNode);

// print xml
echo $dom->saveXml($dom->documentElement);
Run Code Online (Sandbox Code Playgroud)

从技术上讲,你不需要XPath.但是,您的libxml版本可能无法getElementById用于未经验证的文档(ID属性在XML中是特殊的).在这种情况下,调用替换到getElementById

$xp = new DOMXPath($dom);
$oldNode = $xp->query('//div[@id="old_div"]')->item(0);
Run Code Online (Sandbox Code Playgroud)

在键盘上演示


要创建一个$newNode带子节点而不必逐个创建和追加元素,您可以这样做

$newNode = $dom->createDocumentFragment();
$newNode->appendXML('
<div id="new_div">
    <p>some other text</p>
    <p>some other text</p>
    <p>some other text</p>
    <p>some other text</p>
</div>
');
Run Code Online (Sandbox Code Playgroud)