简体   繁体   中英

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.

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. So I use getElementsByTagName to stringify just the body node, but it includes the body node it's self...

<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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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