example, generate an XML document
The code is as follows |
Copy Code |
Class Simplexmlextended extends SimpleXMLElement { Public Function Addcdata ($cdata _text) { $node = Dom_import_simplexml ($this); $no = $node->ownerdocument; $node->appendchild ($no->createcdatasection ($cdata _text)); } } function Array2xml ($array, $xml = False) { if ($xml = = False) { $xml = new simplexmlextended (' <root/> '); } foreach ($array as $key => $value) { if (Is_array ($value)) { Array2xml ($value, $xml->addchild ($key)); }else{ If you include Chinese characters, go to code if (Preg_match ("/([X81-xfe][x40-xfe])/", $value, $match)) { $value = Iconv (' GBK ', ' utf-8 ', $value); } $xml-> $key = NULL; VERY important! We need a node where to append $xml-> $key->addcdata ($value); $xml-> $key->addattribute (' Lang ', ' en '); $xml->addchild ($key, $value); } } return $xml->asxml (); } |
Cases
SimpleXMLElement Parsing xml
code is as follows |
copy code |
<?php $content = <<<xml <?xml version= "1.0" encoding= "UTF-8"?> <test> <global_setting> <ping_protocol>HTTP</ping_protocol> <ping_port>80</ping_port> <ping_path>/index.html</ping_path> <response_timeout>5000</response_timeout> <unhealthy_threshold>2</unhealthy_threshold> </global_setting> <instances> <instance ip= "192.168.234.121"/> <instance ip= "192.168.234.28"/> </instances> </test> XML; $test = new SimpleXMLElement ($content); Get the value of Ping_protocol $ping _protocol = $test->global_setting->ping_protocol; echo "Ping_protocol: $ping _protocol n"; Print out all instance IP foreach ($test->instances->instance as $instance) { echo "IP: {$instance [' IP ']} n"; } |
php: Indicates the earliest version of PHP that supports this function.
function |
Description |
PHP |
__construct () |
Creates a new SimpleXMLElement object. |
5 |
AddAttribute () |
Adds an attribute to the SimpleXML element. |
5 |
AddChild () |
Adds a child element to the SimpleXML element. |
5 |
Asxml () |
Gets the XML string from the SimpleXML element. |
5 |
Attributes () |
Gets the properties of the SimpleXML element. |
5 |
Children () |
Gets the child of the specified node. |
5 |
Getdocnamespaces () |
Gets the namespace of the XML document. |
5 |
GetName () |
Gets the name of the SimpleXML element. |
5 |
GetNamespaces () |
Gets the namespace from the XML data. |
5 |
Registerxpathnamespace () |
Creates a namespace context for the next XPath query. |
5 |
Simplexml_import_dom () |
Gets the SimpleXMLElement object from the DOM node. |
5 |
Simplexml_load_file () |
Gets the SimpleXMLElement object from the XML document. |
5 |
Simplexml_load_string () |
Gets the SimpleXMLElement object from an XML string. |
5 |
XPath () |
Run an XPath query on the XML data. |
5 |