How can I use XPath and DOM to replace a node/element in php?

前端 未结 2 1614
灰色年华
灰色年华 2020-12-05 20:21

Say I have the following html

$html = \'

some text

相关标签:
2条回答
  • 2020-12-05 21:05

    use jquery hide() first to hide particular div and then use append to append new div

    $('#div-id').remove();
    $('$div-id').append(' <div id="new_div">this is new</div>');
    
    0 讨论(0)
  • 2020-12-05 21:13

    Since the answer in the linked duplicate is not that comprehensive, I'll give an example:

    $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);
    

    Technically, you don't need XPath for this. However, it can happen that your version of libxml cannot do getElementById for non-validated documents (id attributes are special in XML). In that case, replace the call to getElementById with

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

    Demo on codepad


    To create a $newNode with child nodes without having to to create and append elements one by one, you can do

    $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>
    ');
    
    0 讨论(0)
提交回复
热议问题