使用DOMDocument,是否可以获取某个DOM中存在的所有元素? [英] Using DOMDocument, is it possible to get all elements that exists within a certain DOM?

查看:251
本文介绍了使用DOMDocument,是否可以获取某个DOM中存在的所有元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,我有一个HTML文件,其中包含许多不同的元素,每个元素具有不同的属性.假设我事先不知道该HTML的外观.

Let's say I have an HTML file with a lot of different elements, each having different attributes. Let's say I do not know beforehand how this HTML will look like.

使用PHP的DOMDocument,如何遍历 ALL 元素并进行修改?我只看到getElementByTagName和getElementById等.我想遍历所有元素.

Using PHP's DOMDocument, how can I iterate over ALL elements and modify them? All I see is getElementByTagName and getElementById etc. I want to iterate through all elements.

例如.假设HTML看起来像这样(只是一个示例,实际上我不知道其结构):

For instance. Let's say the HTML looks like this (just an example, in reality I do not know the structure):

$html = '<div class="potato"><span></span></div>';

我希望能够进行一些简单的DOM修改(例如Javascript):

I want to be able to some simple DOM modification (like in Javascript):

$dom = new DOMDocument();
$dom->loadHTML($html);

// Obviously the code below doesn't work but showcases what I want to achieve
foreach($dom->getAllElements as $element ){
    if(!$element->hasClass('potato')){
       $element->addClass('potato');
    } else{
       $element->removeClass('potato');
    }
}
$html = $dom->SaveHTML();

因此,在这种情况下,我希望生成的html看起来像这样:

So in this instance, I would like the resulting html to look like this:

    $html = '<div><span class="potato"></span></div>';

那么我如何遍历所有元素并在foreach循环中即时进行修改?我真的不想为此使用正则表达式.

So how can I iterate through all elements and do modifications on the fly in an foreach-loop? I really don't want to use regex for this.

推荐答案

您可以使用

You can pass an asterisk * with getElementsByTagName() which returns all elements:

foreach($dom->getElementsByTagName('*') as $element ){

}

手册:

名称
要匹配的标签的本地名称(无名称空间).特殊值*匹配所有标签.

name
The local name (without namespace) of the tag to match on. The special value * matches all tags.

这篇关于使用DOMDocument,是否可以获取某个DOM中存在的所有元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆