Symfony DomCrawler如何在某些元素后插入html?

时间:2018-10-31 04:40:02

标签: php symfony domdocument domcrawler

HTML内容

<div class="card mb-3 template">
    <div class="card-body">
        <div class="row mt-3">
            <div class="col-sm-4">
                <h4>This is title</h4>
            </div>
            <div class="col-sm-8 text-right">
                <button>Close</button>
            </div>
        </div>
    </div>
</div>

我想在div之后插入一个<h4>元素,例如

<div class="col-sm-4">
    <h4>This is title</h4>
    <div class="status"></div>
</div>

在jQuery中非常简单

$('<div class="status"></div>').insertAfter($('.template').find('h4'));

但是,如何在DomCrawler中做到这一点?

$crawler = new \Symfony\Component\DomCrawler\Crawler($html);
$nodes = $crawler->filter('.template');
foreach ($nodes as $node) { // there are multiple template
    // so how to insert the div element after h4
}

1 个答案:

答案 0 :(得分:0)

Symfony DomCrawler只是PHP内置的DOMDocument类的精美包装。使用getNode将获得执行“ insertAfter”方法所需元素的DOMNode对象。

$crawler = new \Symfony\Component\DomCrawler\Crawler($html);
$domDocument = $this->crawler->getNode(0)->parentNode; //this is how you get domDocument

//creating div
$div = $domDocument->createElement('div');
$div->setAttribute('class', 'status');

//adding div after h4 tag
$h4 = $crawler->filter('h4')->getNode(0);
$h4->parentNode->insertBefore( $div, $h4->nextSibling);