Aşağıdaki xtx89 Php'de bir düğüm/elemanın yerini almak için XPath ve DOM'ı nasıl kullanabilirim?
$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>
';
değerine sahip olduğumu ve #old_div
ile aşağıdakileri değiştirmek istiyorum:
$replacement = '<div id="new_div">this is new</div>';
Sonuçların sonucunu vermek için:
$html = '
<div class="website">
<div>
<div id="new_div">this is new</div>
<div id="another_div"></div>
</div>
</div>
';
Kolayca bir kesim var mı Bunu PHP ile yapmak için -ve-yapıştır işlevi?
Tüm Gordon'un yardımları sayesinde son çalışma kodu:
<?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;
?>
olası bir kopyası [Konumunu korurken düğümü değiştirmek için DOMXPath kullanarak ...] (http://stackoverflow.com/questions/640815/using-domxpath-to-replace-a-node-while- konumunun sürdürülmesi) – Gordon
** Hedef düğümün ** bir DOM yöntemiyle ** değiştirilmesi için ** XPath kullanabilirsiniz **. Başlık reddediliyor. –