我的PHP之旅--XML操作

时间:2021-11-05 10:10:26

XML操作

XML主要是做数据存储和WEB服务的,所以我们难免要操作它,这里只介绍PHP的simpleXML方式。

我们要操作的XML:

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE books[
    <!ELEMENT books (book*)>
    <!ELEMENT book (name,author)>
    <!ELEMENT name (#PCDATA)>
    <!ELEMENT author (#PCDATA)>
    <!ATTLIST book id ID #REQUIRED
                    category CDATA #REQUIRED>
    <!ATTLIST name lang (en|zh) 'zh'>
]>
<books>
    <book id='a3' category='后台技术'>
        <name lang='en'>Learn PHP</name>
        <author>Alex</author>
    </book>

    <book id='a4' category='前台技术'>
        <name lang='en'>Learn HTML</name>
        <author>Alex</author>
    </book>  

    <book id='a5' category='前台技术'>
        <name lang='en'>Learn CSS</name>
        <author>Alex</author>
    </book>
</books>

SimpleXMLElement

我们要操作XML需要得到一个SimpleXMLElement对象,方法有两种:

$simple_element = simplexml_load_file('test.xml');
$simple_element = new SimpleXMLElement('test.xml');

添加

$simple_element = simplexml_load_file('test.xml');
// 添加节点
$new_book = $simple_element->addChild('book');
$new_name = $new_book->addChild('name','learn_JAVAScript');
$new_book->addChild('author','Alex');
// 添加属性
$new_book->addAttribute('id','a6');
$new_book->addAttribute('category','前端技术');
// 保存
$simple_element->saveXML('test.xml');

查询

$simple_element = simplexml_load_file('test.xml');
// 编写HTML
$table = '<table width="600" border="1">';
$table .= '<tr><th>title</th><th>author</th></tr>';
foreach ($simple_element->book as $book) {
    $table .= "<tr>";
    $table .= "<td>{$book->name}</td>";
    $table .= "<td>{$book->author}</td>";
    $table .= '</tr>';
}

echo $table;

修改

$simple_element = simplexml_load_file('test.xml');
$books = $simple_element->book;
$books[1]->name = 'PHP经典实例';
$simple_element->saveXML('test.xml');
$simple_element = simplexml_load_file('test.xml');
// 获取到所有的book
$books = $simple_element->book;
// 获取book1的所有属性
$attributes = $books[1]->attributes();
// 修改属性
$attributes['category'] = '工具';
$simple_element->saveXML('test.xml');

删除

$simple_element = simplexml_load_file('test.xml');
// 获取到所有的book
$books = $simple_element->book;
// 删除用unset即可
unset($books[0]);
$simple_element->saveXML('test.xml');