我有以下html
$html = '<body><div style="font-color:#000">Hello</div>
<span style="what">My name is rasid</span><div>new to you
</div><div style="rashid">New here</div></body>';
$dom = new DOMDocument();
$dom->loadHTML($html);
$elements = $dom->getElementsByTagName('body');
我试过了
foreach($elements as $child)
{
echo $child->nodeName;
}
输出是
body
但是我需要遍历body下面的所有标签,而不是body。我该怎么做呢?
我也尝试在上面的例子中替换
$elements = $dom->getElementsByTagName('body');
$elements = $dom->getElementsByTagName('body')->item(0);
但是它给出错误。任何解决方案? ?
try this
$elements = $dom->getElementsByTagName('*');
$i = 1; //counter to output from 3rd one, since foreach loop below will output" html body div span div div"
foreach($elements as $child)
{
if ($i > 2) echo $child->nodeName."<br>"; //output "div span div div"
++$i;
}
如果您只想要body
元素的子节点,您可以使用:
$body = $dom->getElementsByTagName( 'body' )->item( 0 );
foreach( $body->childNodes as $node )
{
echo $node->nodeName . PHP_EOL;
}
如果需要body
元素的所有降序节点,可以使用DOMXPath:
$xpath = new DOMXPath( $dom );
$bodyDescendants = $xpath->query( '//body//node()' );
foreach( $bodyDescendants as $node )
{
echo $node->nodeName . PHP_EOL;
}
使用此代码
$elements = $dom->getElementsByTagName('*');
foreach($elements as $child)
{
echo $child->nodeName;
}