2010-03-19 84 views
2
$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。有人知道为什么我可以清楚地看到编号为galeria_list的元素在$code中。为什么这不能获得元素?PHP Dom不取回元素

此外,有没有人知道如何防止在saveHTML方法中添加<html><body>标记的domdocument?

感谢

回答

1

看来,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(); 
+0

感谢您的代码:) – AntonioCS 2010-03-19 14:33:24

1

你可能会考虑DOMDocumentFragment而不是DOM文档,如果你不想头。

至于ID问题,这是从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是有可能的问题。

+0

我会研究一下。你知道我为什么没有得到这个元素吗? – AntonioCS 2010-03-19 14:19:05

4

似乎loadhtml()不“重视“定义id作为DOM的id属性的html dtd。但是,如果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'));