Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
358 views
in Technique[技术] by (71.8m points)

php - echo innerHTML, without outer node tags

I'm using the DOMDocument class to parse a fairly unpredictable string of markup. It's not all that well formed and I need some data from it. Regex's are right out, of course.
So far, I've got this:

$dom = new DOMDocument;
$dom->loadHTML($str);
$contents = $dom->getElementsByTagName('body')->item(0);
echo $dom->saveXML($contents);

Now this gives me:

<body>
    <p>What I'm really after</p>
    <ul><li>Foo</li><li>Bar</li></ul>
    <h6>And so on</h6>
</body>

What really annoys me are those <body> tags. I want them gone. After grazing the web, I've stumbled across the weirdest workarounds. Some more hacky than others, so in the end, I settled for:

echo substr($dom->saveXML($contents), 6, -7);

Still feels hacky to me, but it's the best I could find. Is there a more reliable way of getting the innerHTML of the DOM, starting from a given node, without the corresponding tags actually showing up?

I've seen suggestions using regex's (a no-no IMHO), or even looping through all the children, echoing those that have childNodes of their own, and stringing together those that don't:

if ($contents->hasChildNodes())
{
    $children = $contents->getElementsByTagName('*');
    foreach($children as $child)
    {
        if ($child->hasChildNodes() || $child->nodeName === 'br')
        {//or isset($standaloneNodes[$child->nodeName])
            echo $dom->saveXML($child);
            continue;
        }

        echo '<'.$child->nodeName.'>'.$child->nodeValue.'</'.$child->nodeName.'>';
    }
}

But that, to me, seems even more absurd...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When exporting HTML, you must have a single root element. In most cases, the most useful one is the body. Since you're loading in an HTML fragment, you know for certain that it won't have any attributes, therefore the substr(...,6,-7) is perfectly predictable and fine.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...