2010-03-19 86 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'));