SimpleXMLElement implements Traversable {
/* 方法 */
final public __construct ( string $data )
public void addAttribute ( string $name [, string $value ] )
public SimpleXMLElement addChild ( string $name [, string $value ] )
public mixed asXML ([ string $filename ] ) 别名:saveXML()
public SimpleXMLElement children ()
public int count ( void )
public array xpath ( string $path )
}
bookstore.xml
<?xml version="1.0" encoding="utf-8" ?>
<bookstore>
<book category="COOKING">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2018</year>
<price>30.00</price>
</book>
<book category="CHILDREN">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2021</year>
<price>29.99</price>
</book>
<book category="WEB">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2022</year>
<price>39.95</price>
</book>
</bookstore>
1.查询
<?php
//[需求]:将bookstore.xml的内容以表格的形式输出。
//得到simplexmlelement对象
//方式1, 使用构造方法, 注意参数是data, 不能文件名
// $data = file_get_contents('bookstore.xml');
// $sxe = new SimpleXMLElement($data);
//方式2, 使用普通的函数来获得对象
$sxe = simplexml_load_file("bookstore.xml");
$res = "<table width='600' border='1'>";
$res .= "<tr><th>title</th><th>author</th><th>year</th><th>price</th></tr>";
foreach($sxe->book as $book){
$res .= "<tr>";
$res .= "<td>{$book->title}</td>";
$res .= "<td>{$book->author}</td>";
$res .= "<td>{$book->year}</td>";
$res .= "<td>{$book->price}</td>";
$res .= "</tr>";
}
$res .= "</table>";
echo $res
?>
2.添加
<?php
//[需求]:在bookstore中增加一本书
$sxe = simplexml_load_file('bookstore.xml');
//添加子元素
$newbook = $sxe->addChild('book'); //注意,此处的sxe就是根节点
$newtitle = $newbook->addChild('title','天龙八部');
$newbook->addChild('author','金庸');
$newbook->addChild('year',1968);
$newbook->addChild('price',59);
//添加属性
$newbook->addAttribute('category','武侠');
$newtitle->addAttribute('lang','tw');
//保存为新的xml
$sxe->asXML('sxe_add_book.xml');
?>
结果如下:
<book category="武侠"><title lang="tw">天龙八部</title><author>金庸</author><year>18968</year><price>59</price></book>
3.更新
<?php
//[需求]:将所有的书籍打2折
$sxe = simplexml_load_file('bookstore.xml');
foreach ($sxe->book as $book){
$book->price *= 0.2;
}
// 指定保存文件
$sxe->asXML('sxe_update_book.xml');
?>
4.删除
<?php
//[需求]:删除所有书籍的year元素
$sxe = simplexml_load_file('bookstore.xml');
foreach ($sxe->book as $book){
unset($book->year);
}
// 指定保存文件
$sxe->asXML('sxe_delete_book.xml');
注意: unset() 销毁指定的变量, 数组元素, 对象均可以删除