在PHP中的foreach循环中修改XML

时间:2015-01-29 12:19:38

标签: php xml foreach

如何在foreach循环中更新/修改XML?

我有这样的XML:

<items>
    <item>
        <client>1</client>
        <retailer>RET1</retailer>
        <code>c553d8be7f3e88bda6a26b8e7eacd11a6001e0ba5f3c6e26ddbf4a08d9e277f3</code>
        <id>1234567891011</id>
    </item>
    <item>
        <client>1</client>
        <retailer>RET1</retailer>
        <code>9afb1b44a582d76159626d05aaf414983625530d83cbfa40a1359bf0afd9225b</code>
        <id>1234567891011</id>
    </item>
    <item>
        <client>1</client>
        <retailer>RET1</retailer>
        <code>90f5ff04e07b0701b6db3c6e44ed2f1636b64fb9eb78f9121dc684b8b8339741</code>
        <id>1234567891011</id>
    </item>
</items>

在我的代码中,我有一个foreach循环:

foreach( $xml as $code )
{
    // Remove each item, so to keep the only one inside, and each time move forward by removing all other items

    // if ($xml->node->code != $code ) 
        // remove it

}

我不知道如何删除每次不等于代码值的节点,是否有任何建议?

2 个答案:

答案 0 :(得分:0)

尝试使用domdocument并删除children以删除节点。

$client = $items->getElementsByTagName('client')->item(0);
$items->removeChild($client);

答案 1 :(得分:0)

你可以这样做:

<?php
$xml = simplexml_load_string($string);//$string contains your xml
$item = $xml->item;
$count_node = count($item);
for($i=0;$i<$count_node;$i++)
{
    echo $item[$i]->code;// access the tags like this and check your conditions
}
?>

如果你坚持任何问题,请告诉我