如何在DOM,PHP中将类添加到img对象? [英] How to add class to an img object in DOM,PHP?
问题描述
这是一段代码
$ doc = new DOMDocument();
$ doc-> loadHTML($ article_header);
$ imgs = $ doc-> getElementsByTagName(’img’);
foreach($ imgs as $ img){
进入 $ imgs
带有DOM img标签。现在,我想通过向其添加一些类来更改原始img标签。
所以,如果 $ article_header
是
一些文本 ...< img src ='http:// some_source'> ...一些文字...
现在我希望它变成这样:
某些文本 ...< img class ='someclass'src ='http:// some_source'> ...某些文本...
更新
<我重复。起始变量为
$ article_header
。 因此必须对其进行所有更改。
使用我的代码,我只搜索 $ article_header
对于img标签,找到它们并将它们放入一些变量中并进行更改就可以了,但是如何将所有更改返回到 $ article_header
???
在您的foreach循环中,调用 $ img-> setAttribute('class','someclass');
。这应该可以解决问题。在 http://docs.php.net/manual/en/domelement中了解更多信息。 setattribute.php
然后,您需要使用 $ article_header = $ doc-> saveXml();保存修改过的文档。
。
Here is piece of code
$doc = new DOMDocument();
$doc->loadHTML($article_header);
$imgs = $doc->getElementsByTagName('img');
foreach ($imgs as $img) {
Into $imgs
goes DOM img tag. Now I want to change the original img tag by adding some class to it.
SO if the $article_header
was this:
"some text"...<img src = 'http://some_source'>...some text...
Now I want it to become this:
"some text"...<img class = 'someclass' src = 'http://some_source'>...some text...
UPDATE
I repeat. Start variable is $article_header
.
So all changes must be done to it.
With my code I just search through $article_header
for img tags , finding them putting them into some variables and change them there is ok, but how can I put all changes back to $article_header
???
In your foreach loop, call $img->setAttribute('class', 'someclass');
. This should do the trick. See more at http://docs.php.net/manual/en/domelement.setattribute.php
Then you need to save the modified document back using $article_header = $doc->saveXml();
.
这篇关于如何在DOM,PHP中将类添加到img对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!