【问题标题】:Replace some elements with a custom content using PHP DOMDocument使用 PHP DOMDocument 将一些元素替换为自定义内容
【发布时间】:2022-01-10 22:31:06
【问题描述】:

我需要在 Wordpress 页面上的 div 部分中替换可变数量的连续段落,该部分仅包含这个 div 部分。我想在服务器端执行此操作。我认为这可以通过the_content() 钩子和DomDocument 类来完成,但我不知道该怎么做。您可以在下面看到div 部分结构。我需要替换的段落在最后一个标题和最后一个段落之间(所以标题和最后一个段落保持不变)。我将不胜感激。

<div id="text-document">
    <h2>a title</h2>
    <p>some content</p>
    <!-- other paragraphs here -->

    <!-- some other DIVs, titles and paragraphs here -->

    <h2>the last title</h2>

    <!-- some paragraphs here -->

    <p>the last paragraph</p>
</div>

DomDocument/Wordpress 部分:

add_filter( 'the_content', function( $content ) {
    $content = mb_convert_encoding( $content, 'HTML-ENTITIES', 'UTF-8' );
    $dom = new DOMDocument( '1.0', 'UTF-8' );
    @$dom->loadHTML( $content );

    //the missing part

    $content = $dom->saveHTML( $dom );

    return $content;
} );

【问题讨论】:

    标签: php html wordpress domdocument


    【解决方案1】:

    如果我对您的理解正确,那么这些方面的内容应该让您至少更接近您想去的地方:

    $xpath = new DOMXPath($dom);
    
    $targets = $xpath->query('//h2[last()]/following-sibling::p[not(position()=last())]');
    
    foreach($targets as $target){
            $target->parentNode->removeChild($target);}
    
    $destination = $xpath->query('//p[last()]');
    $template = $dom->createDocumentFragment();
    $template->appendXML('<p>I am new here</p>');
    $destination[0]->parentNode->insertBefore($template, $destination[0]);
    echo $dom->saveHTML();
    

    【讨论】:

    • 太棒了!我所做的唯一更改是将代码行 $destination = $xpath-&gt;query('//p[last()]'); 更改为 $destination = $xpath-&gt;query('//h2[last()]/following-sibling::p[last()]');。原始代码行保存了另一个位置,而不是最后一段,我想可能是因为目标内容中有两个 div 部分,我错过了提及(对不起!)。非常感谢!
    • @lurie - 很高兴它对你有用!
    猜你喜欢
    • 1970-01-01
    • 2019-11-19
    • 2018-02-18
    • 1970-01-01
    • 2011-01-15
    • 2017-12-22
    • 1970-01-01
    • 2021-12-27
    • 2012-10-24
    相关资源
    最近更新 更多