Log in

View Full Version : using PHP to remove elements from XML file.



JustSuds
10-12-2008, 11:41 AM
I have this xml file, and the php code that builds it using an entry form. however, i urgently need help with some php to delete any specified "book".

this file is "loaned.xml" - I want to be able to enter "Book 1" or "Book 2" into a form and update the xml file by deleting the corresponding entry.

<catalogue>
<resource>
<book>
<ID>Book 1</ID>
<date>today</date>
<retdate>tomorrow</retdate>
<SID>Student 1</SID>
</book>
<book>
<ID>Book 2</ID>
<date>today</date>
<retdate>tomorrow</retdate>
<SID>Student 4</SID>
</book>
</resource>
</catalogue>

Please help! I've tried and failed with so many internet solutions so far.

techietim
10-12-2008, 03:54 PM
Make sure you have PHP 5+


function delete_book_id($id, $filename = 'loaned.xml'){
$data = simplexml_load_file($filename);
for($i = 0, $length = count($data->resource->book); $i < $length; $i++){
if($data->resource->book[$i]->ID == $id){
unset($data->resource->book[$i]);
break;
}
}
file_put_contents($filename, $data->saveXML());
}
//SAMPLE USAGE
delete_book_id('Book 1');