您需要确定您的 xml 是关于书籍还是关于作者。
如果是关于书籍,那么它应该看起来像这样:-
<?xml version="1.0"?>
<books>
<book>
<title>Beginning iOS 4 Application Development</title>
<author>WeiMengLee</author>
</book>
</books>
然后,您可以像这样添加一本新书:-
$xml = new SimpleXMLElement("filename.xml", null, true);
$book = $xml->addChild('book');
$book->addChild('title', 'Another Book');
$book->addChild('Author', 'WeiMengLee');
$xml->asXML('filename.xml');
输出:-
<?xml version="1.0"?>
<books>
<book>
<title>Beginning iOS 4 Application Development</title>
<author>WeiMengLee</author>
</book>
<book>
<title>Another Book</title>
<Author>WeiMengLee</Author>
</book>
</books>
另一方面,如果您的 xml 是关于作者的,那么它应该看起来像这样:-
<?xml version="1.0"?>
<authors>
<author>
<name>WeiMengLee</name>
<books>
<book>Beginning iOS 4 Application Development</book>
</books>
</author>
</authors>
你会像这样添加另一本书:-
$xml = new SimpleXMLElement("filename.xml", null, true);
foreach($xml as $author){
if($author->name == 'WeiMengLee'){
$weimenglee = $author;
}
}
$weimenglee->books->addChild('book', 'Another book');
$xml->asXML('filename.xml');
输出:-
<?xml version="1.0"?>
<authors>
<author>
<name>WeiMengLee</name>
<books>
<book>Beginning iOS 4 Application Development</book>
<book>Another book</bmook>
</books>
</author>
</authors>