简体   繁体   English

PHP DOMDocument-将节点的子节点保存为字符串-不包括父节点

[英]PHP DOMDocument - save children of a node to string - excluding the parent node

I'm loading up an HTML fragment into a DOMDocument, modifying it, and then converting back to a string. 我正在将HTML片段加载到DOMDocument中,对其进行修改,然后再转换回字符串。

The closest I can get is this... 我能得到的最接近的是这个...

$html_string = "<b>my html fragment</b><div>more child nodes</div>";
$doc_html = new DOMDocument();
$doc_html->loadHTML( $html_string );
//do stuff
$html_string = $doc_html->saveHTML( $doc_html->getElementsByTagName('body')->item(0) );

The problem here is that loadHTML wraps it in a <html> and <body> tag. 这里的问题是loadHTML将其包装在<html><body>标记中。 So I use getElementsByTagName to stringify just the body node, but it includes the body node it's self... 所以我使用getElementsByTagName仅对主体节点进行字符串化,但是它包括主体节点本身。

<body><b>my html fragment</b><div>more child nodes</div></body>

But i just want the child nodes like the input string. 但是我只希望子节点喜欢输入字符串。

Other than looping all children and concatenating a string / running a req ex on the resulting string, is there a simple way to do this? 除了循环所有子级并连接字符串/在结果字符串上运行req ex之外,还有一种简单的方法吗?

m

<?php
$doc = doc();
$xp = new DOMXpath($doc);
$nl = $xp->query('//a');
foreach($nl as $n) {
    $df = $doc->createDocumentFragment();
    $nodes = array();
    foreach( $n->childNodes as $cn ) {
        $nodes[] = $cn;
    }
    foreach($nodes as $cn) {
        $df->appendChild(   $cn );
    }
    echo $doc->savexml( $df );
}


function doc() {
    $doc = new DOMDocument;
    $doc->loadxml(<<< eox
<doc>
    <a>
        <b>1</b>
        <b>2</b>
        <b>3</b>
        <b>4</b>
    </a>
</doc>
eox
    );
    return $doc;
}

prints 版画

    <b>1</b>
    <b>2</b>
    <b>3</b>
    <b>4</b>

see http://docs.php.net/domdocumentfragment 参见http://docs.php.net/domdocumentfragment

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM