删除xml节点取决于多个数组?

时间:2010-12-22 08:15:54

标签: php

删除xml节点取决于多个数组?

我的原始xml文件(original.xml)

  <books>    
        <book>
            <qty>12</qty>
            <title>C++</title>
        </book>
        <book>
            <qty>21</qty>
            <title>PHP</title>
        </book>    
      </books>    
      <books>    
        <book>
            <qty>25</qty>
            <title>Java</title>
        </book>    
        <book>  
            <qty>32</qty>
            <title>Python</title>
        </book>
        <book>  
            <qty>22</qty>
            <title>History</title>
        </book>    
     </books>

我有一个数组使用操作到新的xml文件(new.xml)

$arr = Array (
    [0] => Array (
        [0] => 12;C++
        [1] => 21;PHP
    )    
    [1] => Array (
        [0] => 25;java
        [1] => 32;Python
    )
)

取决于数组==&gt; new.xml将变成这样:

//tag `<book>` block has removed because it contain all elements in an array ($arr)

<books>
    <book>  
        <qty>22</qty>
        <title>History</title>
    </book>
</books>

1 个答案:

答案 0 :(得分:1)

您可以使用DOMDocument和XPath从XML树中删除元素:

$str = '<content>'.$xml.'</content>';

$doc = new DOMDOcument;
$doc->loadxml($str);

$xpath = new DOMXpath($doc);

$arr = array(
    array('12;C++', '21;PHP'),
    array('25;java', '32;python')
);

# Remove elements based on qty and title
foreach($arr as $items) {
    foreach($items as $item) {
        list($qty, $title) = explode(';', $item);
        foreach($xpath->query('/content/books/book[title="'.$title.'"][qty="'.$qty.'"]') as $book) {
            $book->parentNode->removeChild($book);
        }
    }
}

# Remove empty <books>
foreach($xpath->query('books[count(book)=0]') as $empty) {
    $empty->parentNode->removeChild($empty);
}

header('Content-type: text/xml');
echo $doc->savexml();