English 中文(简体)
Dom Dom 文档 - 提取文档 ID 保存
原标题:Dom Document - extract a document id & save

我正试图用 dom 文档提取一个特定的 HTML 组合 。

我的代码如下:

    $domd = new DOMDocument( 1.0 ,  utf-8 );
    $domd->loadHTML($string);
    $this->hook =  content ;
    if($this->hook !==   ) {
        $main = $domd->getElementById($this->hook);
        $newstr = "";
        foreach($main->childNodes as $node) {
            $newstr .= $domd->saveXML($node, LIBXML_NOEMPTYTAG);
        }
        $domd->loadHTML($newstr);
    }
    //MORE PARSING USING THE DOMD OBJECT

这效果很好,但每个前方都相当缓慢, 我在想是否有更聪明的方法这样做。 我正在把HTML 重新装入$D, 这样我就可以继续编辑。 在我脑海里,我觉得我应该保存一个碎片,而不是把节省下来的$Newstr 重新装入这个对象。

这能更优雅或更快吗?

谢谢!

最佳回答

我假设你想要变换你现有的 $domd 文档, 用您从内容节点中抓取的子节点来完全替换它 :

UPDATE: just realize:由于您正在使用 loadHTML 重新装入,您可能想要保存它创建的 html / body 节点。 以下代码已被调整为空 body , 并在此附加碎片 :

$domd = new DOMDocument( 1.0 ,  utf-8 );
$domd->loadHTML($string);
$this->hook =  content ;
if($this->hook !==   ) {
    $main = $domd->getElementById($this->hook);
    $fragment = $domd->createDocumentFragment();
    while($main->hasChildNodes()) {
        $fragment->appendChild($main->firstChild);
    }
    $body = $domd->getElementsByTagName("body")->item(0);
    while($body->hasChildNodes()) {
        $body->removeChild($body->firstChild);
    }
    $body->appendChild($fragment);
}
//MORE PARSING USING THE DOMD OBJECT
问题回答

暂无回答




相关问题
Template Classes in C++ ... a required skill set?

I m new to C++ and am wondering how much time I should invest in learning how to implement template classes. Are they widely used in industry, or is this something I should move through quickly?

JSON with classes?

Is there a standardized way to store classes in JSON, and then converting them back into classes again from a string? For example, I might have an array of objects of type Questions. I d like to ...

Object-Oriented Perl constructor syntax and named parameters

I m a little confused about what is going on in Perl constructors. I found these two examples perldoc perlbot. package Foo; #In Perl, the constructor is just a subroutine called new. sub new { #I ...

Passing another class amongst instances

I was wondering what is the best practice re. passing (another class) amongst two instances of the same class (lets call this Primary ). So, essentially in the constructor for the first, i can ...

Where can I find object-oriented Perl tutorials? [closed]

A Google search yields a number of results - but which ones are the best? The Perl site appears to contain two - perlboot and perltoot. I m reading these now, but what else is out there? Note: I ve ...

热门标签