PHP Dom不检索元素 [英] PHP Dom not retrieving element
问题描述
$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
。有人知道为什么吗我可以在 $ code
中清楚地看到ID为$ code> galeria_list 的元素。为什么没有获取元素?
The var_dump
always returns NULL
. Anyone know why? I can clearly see the element with the id galeria_list
in $code
. Why is this not getting the element?
还有,有谁知道如何防止domdocument添加< html> $
saveHTML
方法中的c $ c>和< body>
标签
And also, does anyone know how to prevent the domdocument from adding the <html>
and <body>
tags on the saveHTML
method?
谢谢
推荐答案
似乎 DOMDocument
不会用HTML片段播放很好。您可能要考虑 DOMDocumentFragment
(as dnagirl建议)或考虑扩展 DOMDocument
。
It seems that the DOMDocument
will not play nice with HTML fragments. You may want to either consider the DOMDocumentFragment
(as dnagirl suggests) or consider extending the DOMDocument
.
经过一番研究我已经把一个简单的扩展组合在一起,可以实现你所要求的:
After a little research, I've put together a simple extension that will achieve what you are asking:
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);
}
}
h1>
Usage
$dom = new MyDOMDocument();
$dom->loadHTML($code);
var_dump($dom->getElementById("galeria_list"));
echo $dom->output();
这篇关于PHP Dom不检索元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!