2012-05-16 4 views
2

는 :PHP DOMDocument를 사용하여 속성을 제거하는 방법은 무엇입니까? XML이 조각으로

<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 
    } 
} 

?> 

나는 foreach는 블록 내 속성에서 제거하려고 할 때 내부 포인터를 분실하고 속성을 모두 삭제하지 않습니다처럼 어떻게 든, 그것은 보인다.

다른 방법이 있습니까? 사전에

감사합니다.

답변

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

빙고! 첫 번째 방법을 사용하고 있습니다. 고마워요! (다른 두 사람도 잘 작동합니다) – romulodl

관련 문제