0

Remove xml node depend on an multiple array?

My original xml file like this(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>

I have an array use manipulate to new xml file(new.xml)

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

Depend above array ==> new.xml will become like this:

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

<books>
    <book>  
        <qty>22</qty>
        <title>History</title>
    </book>
</books>
2
  • 1
    All book elements should have the same tag <book>, not <book_1>, <book_2> etc... Commented Dec 22, 2010 at 8:22
  • @Tatu exactly. <books><book/><book/></books> is the right way to do it. If each book needs to be numberd it should be an attribute: <books><book id="1"/><book id="2"/></books> Commented Dec 22, 2010 at 8:25

1 Answer 1

1

You can use DOMDocument and XPath to remove elements from a XML tree:

$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();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.