sagen, dass ich die folgende htmlWie kann ich XPath und DOM verwenden, um einen Knoten/Element in PHP zu ersetzen?
$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>
';
Und ich möchte ersetzen #old_div
mit der folgenden haben:
$replacement = '<div id="new_div">this is new</div>';
zu geben, ein Endergebnis von:
$html = '
<div class="website">
<div>
<div id="new_div">this is new</div>
<div id="another_div"></div>
</div>
</div>
';
Gibt es eine einfache Cut-and-Paste-Funktion für das mit PHP?
Abschlussarbeits Code Dank an alle Gordon Hilfe:
<?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;
?>
möglich Duplikat von [Verwenden von DOMXPath zum Ersetzen eines Knotens unter Beibehaltung seiner Position ...] (http://StackOverflow.com/questions/640815/using-domxpath-to-replace-a-node-while- Aufrechterhaltung-seiner-Position) – Gordon
Sie können ** XPath verwenden, um ** den Zielknoten auszuwählen, den ** durch eine DOM-Methode ersetzen soll **. Titel wird neu geschrieben. –