echo innerHTML, without outer node tags

我只是一个虾纸丫 提交于 2019-12-28 07:06:31

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/16840683/echo-innerhtml-without-outer-node-tags

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!