2011-03-30 114 views
0

每个人,使用PHP:需要删除所有匹配的XML节点

道歉为简单起见。当我在C#和SQL Server中更舒适时,我正在使用PHP和XML进行一次性快速的一次性操作。

我有一个看起来像这样的XML文件:

<items> 
    <item> 
     <name>Item A</name> 
     <sort>2</sort> 
    </item> 

    <item> 
     <name>Item B</name> 
     <sort>3</sort> 
    </item> 

    <item> 
     <name>Item C</name> 
     <sort>1</sort> 
    </item> 
</items> 

我需要删除所有的排序节点,这样:

<items> 
    <item> 
     <name>Item A</name> 
    </item> 

    <item> 
     <name>Item B</name> 
    </item> 

    <item> 
     <name>Item C</name> 
    </item> 
</items> 

应该很简单吧?

+0

Duplicate http://stackoverflow.com/questions/4177376/delete-all-elements-of-a-certain-type-from-an-xml-doc-using-php – Gordon 2011-03-30 19:08:16

+0

谢谢戈登。除了那一个,我一定读过每一篇文章。对不起,重复 - 尽管希望有需要的人会看到这一点。 – ropadope 2011-03-30 19:20:16

回答

0

是...

$xml = simplexml_load_file('test.xml'); 
foreach($xml->item as $item) { 
     unset($item->sort); 
} 
echo $xml->asXml(); 

测试这个.. simplexml的是在我看来,更容易。然后你会写“$ xml-> asXML()”到你的文件中。

+0

感谢您的快速回答。戈登的链接http://stackoverflow.com/questions/4177376/delete-all-elements-of-a-certain-type-from-an-xml-doc-using-php作为重复完全按照需要在我的实例中工作。 – ropadope 2011-03-30 19:21:15

+0

没问题,我也用simplexml更新了我的答案。它实际上工作。 ;) – 2011-03-30 19:22:48

+0

我更喜欢这个。再次感谢! – ropadope 2011-03-30 19:28:55