开发者

Manipulating XML with PHP

I have an XML file that looks like this

<library>
   <book>
      <title>Title</title>
      <author>author</author>
      <price>20</price>
   <book>
<library>

I want to be able to add a book and be able to change the price.

Does anybody have any incite on how to do this?

Everywhere were i look keeps ref开发者_StackOverflow中文版erring to "simpleXML" however I can only figure out how to create the original file i cant seem to figure out how to edit.


Yeah, i kinda agree that xml libraries documentation in PHP is not so intuitive to get going with.

$xml = simplexml_load_file("file.xml"); 

//add   
$book = $xml->addChild("book"); 
$book->addChild("title", "TTT"); 
$book->addChild("author", "AAA"); 
$book->addChild("price", 123); 

//edit 1st:
$xml->book[0]->price = "priceless";

//write result
$xml->asXML("result.xml");


Use simplexml_load_string or simplexml_load_file to read a file into an object you can work with.


I use:

$simpleXML = new SimpleXMLElement($stringXML);

To add a value you could:

$simpleXML->addChild('Value', $value);

then to get a string back:

$stringXML = $simpleXML->asXML();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜