我应该如何在php中使用dom获得像这样的div内容?
问题描述:
div就是这样
<div style="width:90%;margin:0 auto;color:#Black;" id="content">
this is text, severaltags
</div>
我应该如何在php中使用dom获取div的内容,包括
标记?
how should i get the div's content including the
tags using dom in php?
答
假设您使用的是PHP5,则可以使用 DOMDocument
-注意这没有提供检索元素内部html的简单方法。您可以执行以下操作:
Assuming your using PHP5 you can use DOMDocument
-- take note that this doesn't provide simple means for retrieving inner html of an element. You can do something along the following:
function DOMinnerHTML($element)
{
$innerHTML = "";
$children = $element->childNodes;
foreach ($children as $child)
{
$tmp_dom = new DOMDocument();
$tmp_dom->appendChild($tmp_dom->importNode($child, true));
$innerHTML.=trim($tmp_dom->saveHTML());
}
return $innerHTML;
}
$dom = new DOMDocument();
$dom->loadHTML($html);
$items = $dom->getElementsByTagName('div');
if ($items->length)
{
$innerHTML = DOMinnerHTML($items->item(0));
}
echo $innerHTML;
对于这种简单的东西,尽管我通常不建议这样做,但我会使用正则表达式:
For something this simple, although I don't normally recommend it, I'd use regex:
preg_match('|<div[^>]+>(.*?)</div>|is', $html, $match);
if ($match)
{
echo 'html is: ' . $match[1][0];
}