( ! ) Warning: include(): http:// wrapper is disabled in the server configuration by allow_url_include=0 in D:\www\up\php\php_xml_simplexml.php on line 18
Call Stack
#TimeMemoryFunctionLocation
10.0000360104{main}( )...\php_xml_simplexml.php:0

( ! ) Warning: include(http://pub.houheaven.com/Nav02/Nav_deep2.htm): failed to open stream: no suitable wrapper could be found in D:\www\up\php\php_xml_simplexml.php on line 18
Call Stack
#TimeMemoryFunctionLocation
10.0000360104{main}( )...\php_xml_simplexml.php:0

( ! ) Warning: include(): Failed opening 'http://pub.houheaven.com/Nav02/Nav_deep2.htm' for inclusion (include_path='.;C:\php\pear') in D:\www\up\php\php_xml_simplexml.php on line 18
Call Stack
#TimeMemoryFunctionLocation
10.0000360104{main}( )...\php_xml_simplexml.php:0

XML 是一个很实用的东西,存储数据、交换数据都很方便,但如何对 XML 进行基本的操作呢?

对 XML 的操作包括创建 XML 文档,添加、查看、修改、删除数据,操作方法有很多种,可以使用 DOMDocument 类、SimpleXML 等都可以实现,本文介绍的是通过 SimpleXML 进行操作。

注意,这个类和下面方法的优势在于它的数据读取和转换,不太适合节点的操作。

官方帮助文档:点此查看


SimpleXML

SimpleXML 扩展提供了一个非常简单和易于使用的工具集,能将 XML 转换成一个带有一般属性选择器和数组迭代器的对象。

方法返回值类型说明
addAttribute(name[,value,namespace])添加属性
addChild(name[,value,namespace])节点添加元素
asXML([file])节点保存 XML 文档

注意:以上的方法只是此类的一部分,比较常用和实用,点此 查看全部


SimpleXML 函数

读取一个文件   :simplexml_load_file

读取一个字符串:simplexml_load_string


①. simplexml_load_file(file)

说明:此函数将一个 XML 文档的内容导入进来,然后转化为对象,作为返回值返回。

XML:language.xml(打开

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

<languages>

<langauge>

<name>Chinese</name>

<use>China</use>

</language>

<langauge>

<name>English</name>

<use>America、England</use>

</language>

</languages>

PHP:readxml.php(打开
    
    $XML=simplexml_load_file("language.xml");	// 读取文件,返回一个可读取对象
    
    echo "<pre>";				// 格式化输出,便于浏览
    print_r($XML);				// 打印整个对象
    
    echo $XML->language[0]->name;		// 打印对象里面的内容
    
结果:打开
    
    SimpleXMLElement Object
    (
        [language] => Array
            (
                [0] => SimpleXMLElement Object
                    (
                        [name] => Chinese
                        [use] => China
                    )
    
                [1] => SimpleXMLElement Object
                    (
                        [name] => English
                        [use] => America、England
                    )
    
            )
    
    )
    Chinese
    

②. simplexml_load_string()

说明:此函数将一个 XML 字符串导入进来,然后转化为对象,作为返回值返回。

PHP:readxml.php(打开
    
    $str = "<?xml version='1.0'?>
	    <root>
	    <child>music</child>
	    <child>movie</child>
	    <child>image</child>
	    </root>";
        
    $xml=simplexml_load_string($str);

    echo "<pre>";
    print_r($xml);
    
    echo $xml->child[0];
    
结果:打开
    
    SimpleXMLElement Object
    (
        [child] => Array
            (
                [0] => music
                [1] => movie
                [2] => image
            )
    
    )
    music
    

显示框架
显示框架
显示框架
显示框架