2012-05-16 4 views
2

С этой частью XML:Как удалить атрибуты с помощью PHP DOMDocument?

<my_xml> 
    <entities> 
    <image url="lalala.com/img.jpg" id="img1" /> 
    <image url="trololo.com/img.jpg" id="img2" /> 
    </entities> 
</my_xml> 

Я должен избавиться от всех атрибутов в пределах тегов изображений. Таким образом, я сделал это:

<?php 

$article = <<<XML 
<my_xml> 
    <entities> 
    <image url="lalala.com/img.jpg" id="img1" /> 
    <image url="trololo.com/img.jpg" id="img2" /> 
    </entities> 
</my_xml> 
XML; 

$doc = new DOMDocument(); 
$doc->loadXML($article); 
$dom_article = $doc->documentElement; 
$entities = $dom_article->getElementsByTagName("entities"); 

foreach($entities->item(0)->childNodes as $child){ // get the image tags 
    foreach($child->attributes as $att){ // get the attributes 
    $child->removeAttributeNode($att); //remove the attribute 
    } 
} 

?> 

Как-то, когда я пытаюсь удалить из атрибута в блоке Еогеаспа, это выглядит как внутренний указатель теряется и не удаляет как атрибутов.

Есть ли другой способ сделать это?

Заранее спасибо.

ответ

7

Изменение внутренней foreach петля для:

while ($child->hasAttributes()) 
    $child->removeAttributeNode($child->attributes->item(0)); 

или обратно к передней делеции:

if ($child->hasAttributes()) { 
    for ($i = $child->attributes->length - 1; $i >= 0; --$i) 
    $child->removeAttributeNode($child->attributes->item($i)); 
} 

Или сделать копию списка атрибутов:

if ($child->hasAttributes()) { 
    foreach (iterator_to_array($child->attributes) as $attr) 
    $child->removeAttributeNode($attr); 
} 

Любой из тех, будет работать.

+0

BINGO! Я использую первый подход. Большое спасибо! (два других тоже хорошо работают) – romulodl

Смежные вопросы