代码之家  ›  专栏  ›  技术社区  ›  AntonioCS

PHP Dom未检索元素

  •  2
  • AntonioCS  · 技术社区  · 16 年前
    $code = '
    <h1>Galeria </h1>
    
    <div class="galeria">
        <ul id="galeria_list">
            <li>
              <img src="img.jpg" width="350" height="350" />
              <br />
              Teste
            </li>
        </ul>
    </div>';
    
    
    $dom = new DOMDocument;
    $dom->validateOnParse = true;
    
    $dom->loadHTML($code);
    
    var_dump($dom->getElementById('galeria_list'));
    

    这个 var_dump NULL . 有人知道为什么吗?我可以清楚地看到id为的元素 galeria_list 在里面 $code

    还有,有人知道如何防止domdocument添加 <html> <body> 上的标签 saveHTML 方法?

    4 回复  |  直到 13 年前
        1
  •  1
  •   Community Mohan Dere    9 年前

    DOMDocument 不会很好地处理HTML片段。你可能想考虑一下 DOMDocumentFragment dnagirl suggests )或考虑扩展 DOMDocument公司 .

    经过一点研究,我整理了一个简单的扩展,可以满足您的要求:

    class MyDOMDocument extends DOMDocument {
    
        function getElementById($id) {
    
            //thanks to: http://www.php.net/manual/en/domdocument.getelementbyid.php#96500
            $xpath = new DOMXPath($this);
            return $xpath->query("//*[@id='$id']")->item(0);
        }
    
        function output() {
    
            // thanks to: http://www.php.net/manual/en/domdocument.savehtml.php#85165
            $output = preg_replace('/^<!DOCTYPE.+?>/', '',
                    str_replace( array('<html>', '</html>', '<body>', '</body>'),
                            array('', '', '', ''), $this->saveHTML()));
    
            return trim($output);
    
        }
    
    }
    

    $dom = new MyDOMDocument();
    $dom->loadHTML($code);
    
    var_dump($dom->getElementById("galeria_list"));
    
    echo $dom->output();
    
        2
  •  4
  •   VolkerK    16 年前

    loadhtml()似乎没有“附加”定义 id 作为DOM的id属性。但是,如果html文档包含DOCTYPE声明,它将按预期工作(但我猜你不想添加doctype和html框架,不管怎样:)。

    $code = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
    <html><head><title>...</title></head>
    <body>
      <h1>Galeria </h1>
      <div class="galeria">
        <ul id="galeria_list">
          <li>
            <img src="img.jpg" width="350" height="350" />
            <br />
            Teste
          </li>
        </ul>
      </div>
    </body></html>';
    
    $dom = new DOMDocument;
    $dom->loadhtml($code);
    var_dump($dom->getElementById('galeria_list'));
    
        3
  •  1
  •   dnagirl    16 年前

    你可以考虑 DOMDocumentFragment

    至于身份问题,这是从 manual :

    <?php
    
    $doc = new DomDocument;
    
    // We need to validate our document before refering to the id
    $doc->validateOnParse = true;
    $doc->Load('book.xml');
    
    echo "The element whose id is books is: " . $doc->getElementById('books')->tagName . "\n";
    
    ?> 
    

    validateOnParse 很可能是个问题。

    推荐文章