我有以下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
但是我需要遍历身体下面的所有标签而不是身体。我怎么能这样做。
我也在上面的例子中尝试过替换
$elements = $dom->getElementsByTagName('body');
带
$elements = $dom->getElementsByTagName('body')->item(0);
但它给出了错误。任何解决方案??
答案 0 :(得分:2)
试试这个
$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;
}
答案 1 :(得分:1)
使用此代码
$elements = $dom->getElementsByTagName('*');
foreach($elements as $child)
{
echo $child->nodeName;
}
答案 2 :(得分:1)
如果您只想要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;
}