使用DOMDocument
- 如果您想再次执行类似操作,我已将代码写入函数:
function DOMinnerHTML(DOMNode $element)
{
$innerHTML = "";
$children = $element->childNodes;
foreach ($children as $child)
{
$innerHTML .= $element->ownerDocument->saveHTML($child);
}
return $innerHTML;
}
function getElContentsByTagClass($html,$tag,$class)
{
$doc = new DOMDocument();
$doc->loadHTML($html);//Turn the $html string into a DOM document
$els = $doc->getElementsByTagName($tag); //Find the elements matching our tag name ("div" in this example)
foreach($els as $el)
{
//for each element, get the class, and if it matches return it's contents
$classAttr = $el->getAttribute("class");
if(preg_match('#\b'.$class.'\b#',$classAttr) > 0) return DOMinnerHTML($el);
}
}
//Calling it:
$html = '<div class="x-ic test"><div class="abc">Test</div><table>.......</table><p>....</p><div style="margin:5px;"></div></div>';
$ret = getElContentsByTagClass($html,'div','x-ic test');//<div class="abc">Test</div><table>.......</table><p>....</p><div style="margin:5px;"></div>
PHP 小提琴- 运行 (F9)