PHP XML常用函数的集合
本文将介绍一些PHP中常用的XML处理函数,让您可以更加方便地处理XML文件。
xml_parser_create()
xml_parser_create
是用来创建一个新的XML解析器的PHP函数,其用法如下:
$parser = xml_parser_create();
xml_parser_set_option()
xml_parser_set_option
可以用来设置XML解析器的选项,其参数包括解析器、选项和选项值:
xml_parser_set_option($parser, $option, $value);
其中 option
可取常数 XML_OPTION_CASE_FOLDING
(是否将标签名小写化)和 XML_OPTION_SKIP_WHITE
(是否跳过空格符等空白字符)。
xml_parse()
xml_parse
是用来解析XML文档的函数,其参数包括解析器和要解析的XML文档:
xml_parse($parser, $xml_data);
其中 xml_data
是要解析的文本数据。
xml_parser_free()
xml_parser_free
可以用来释放XML解析器所占用的内存,其参数为解析器:
xml_parser_free($parser);
示例一
下面的示例代码演示了一个简单的XML解析:
$parser = xml_parser_create();
xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, true);
xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, true);
$xml_data = '
<note>
<to>Tove</to>
<from>Jane</from>
<heading>Reminder</heading>
<body>Don\'t forget me this weekend!</body>
</note>';
xml_parse_into_struct($parser, $xml_data, $xml_arr);
xml_parser_free($parser);
print_r($xml_arr);
此示例将返回如下的XML数组:
Array
(
[0] => Array
(
[tag] => NOTE
[type] => open
[level] => 1
[attributes] => Array
(
)
)
[1] => Array
(
[tag] => TO
[type] => complete
[level] => 2
[attributes] => Array
(
)
[value] => Tove
)
[2] => Array
(
[tag] => FROM
[type] => complete
[level] => 2
[attributes] => Array
(
)
[value] => Jane
)
[3] => Array
(
[tag] => HEADING
[type] => complete
[level] => 2
[attributes] => Array
(
)
[value] => Reminder
)
[4] => Array
(
[tag] => BODY
[type] => complete
[level] => 2
[attributes] => Array
(
)
[value] => Don't forget me this weekend!
)
[5] => Array
(
[tag] => NOTE
[type] => close
[level] => 1
[attributes] => Array
(
)
)
)
示例二
下面的示例代码演示了如何使用PHP将XML字符串转换成对象:
$xml_data = '
<book>
<title>Advanced PHP Programming</title>
<author>
<first_name>George</first_name>
<last_name>Schlossnagle</last_name>
</author>
<price>39.99</price>
<description>
Leading PHP expert George Schlossnagle teaches you to write powerful, optimized PHP code using the latest techniques: dynamic typing, lazy evaluation, advanced dynamic memory management, and more!
</description>
</book>';
$book_obj = simplexml_load_string($xml_data);
print_r($book_obj);
此示例将返回如下的对象:
SimpleXMLElement Object
(
[title] => Advanced PHP Programming
[author] => SimpleXMLElement Object
(
[first_name] => George
[last_name] => Schlossnagle
)
[price] => 39.99
[description] => Leading PHP expert George Schlossnagle teaches you to write powerful, optimized PHP code using the latest techniques: dynamic typing, lazy evaluation, advanced dynamic memory management, and more!
)
以上就是一些常用的PHP XML处理函数的介绍,希望对您有所帮助。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:php xml常用函数的集合(比较详细) - Python技术站