Results 1 to 2 of 2

Thread: using PHP to remove elements from XML file.

  1. #1
    Join Date
    Oct 2008
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default using PHP to remove elements from XML file.

    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.
    Code:
    <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.

  2. #2
    Join Date
    Jul 2008
    Posts
    199
    Thanks
    6
    Thanked 58 Times in 57 Posts

    Default

    Make sure you have PHP 5+
    PHP Code:
    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'); 

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •