I want to modify the existing data in xml file using php
本问题已经有最佳答案,请猛点这里访问。
这是我的 xml 文件
1 2 3 4 5 6 7 8 9 10 11 12 | <books> <book> Jack Herrington</author> PHP Hacks <publisher>O'Reilly</publisher> </book> <book> Jack Herrington</author> Podcasting Hacks <publisher>O'Reilly</publisher> </book> </books> |
我需要使用 php 脚本将第二个标题
任何人都可以给我一个建议。谢谢
文件\\'test.php\\':
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <?php include 'books.php'; $b=new books(); //1. load books from xml to array $arr=$b->load('books.xml'); //2. modify title for($i=0,$ms=count($arr);$i<$ms;$i++) { if($arr[$i]['fields']['title']=='Podcasting Hacks') { $arr[$i]['fields']['title']='Podcasting Pops'; } } //3. save array to xml $b->save('out.xml',$arr); ?> |
文件\\'books.php\\':
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | <?php class books { //load books from xml to array public function load($fname) { $doc=new DOMDocument(); if($doc->load($fname)) $res=$this->parse($doc); else throw new Exception('error load XML'); return $res; } private function parse($doc) { $xpath = new DOMXpath($doc); $items = $xpath->query("book"); $result = array(); foreach($items as $item) { $result[]=array('fields'=>$this->parse_fields($item)); } return $result; } private function parse_fields($node) { $res=array(); foreach($node->childNodes as $child) { if($child->nodeType==XML_ELEMENT_NODE) { $res[$child->nodeName]=$child->nodeValue; } } return $res; } //save array to xml public function save($fname, $rows) { $doc = new DOMDocument('1.0','utf-8'); $doc->formatOutput = true; $books = $doc->appendChild($doc->createElement('books')); foreach($rows as $row) { $book=$books->appendChild($doc->createElement('book')); foreach($row['fields'] as $field_name=>$field_value) { $f=$book->appendChild($doc->createElement($field_name)); $f->appendChild($doc->createTextNode($field_value)); } } file_put_contents($fname, $doc->saveXML()); } } ?> |