如何在php中删除特定id的xml节点

时间:2014-04-08 05:26:54

标签: php xml

这是php代码

    <?php
     function delete_book_id($id, $filename = 'books.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('$id');
   ?>  

XML文件如下

<?xml version="1.0" encoding="utf-8"?>
<catalogue>
<resource>
  <book>
     <ID>Book 1</ID>
     <date>today</date>
     <retdate>tomorrow</retdate>
     <SID>Student 1</SID>
  </book>
   <book>
     <ID>Book 2</ID>
     <date>toda</date>
     <retdate>tomorro</retdate>
     <SID>Student 2</SID>
  </book>

  </resource>
  </catalogue>

请帮我解答。

1 个答案:

答案 0 :(得分:2)

以下更改:

delete_book_id('$id');

要:

delete_book_id($id);

为我工作。