How to parse XML files with PHP

Source: Internet
Author: User
Tags foreach documentation xml parser

DomElement

DomElement domdocument::createelement (String $name [, String $value])

Creating node elements
String $name: Section Roll Call
String $value: Value of Node
8. Add nodes
domnode domnode::appendchild (Domnode $newnode)
Add child nodes
Domnode $newnode: New node
In DOM operations, additions and deletions must depend on the parent node
9, Save
string Domdocument::savexml
Save to a string
int Domdocument::save (string $filename)
Save to a file
String $filename: File name
10, delete the node
domnode domnode::removechild (Domnode $oldnode)
Delete a node
Domnode $oldnode: The node to be deleted
11, Update the node

domnode domnode::replacechild (Domnode $newnode, Domnode $oldnode)
Domnode $newnode: New node
Domnode $oldnode: Original node

12, add properties
domattr Domelement::setattribute (String $name, String $value)
String $name: Property name
String $value: Property value
13, modify the property
Domattr Domelement::setattribute (String $name, String $value)
String $name: Property name
String $value: Property value
14. Delete Attributes
bool Domelement::removeattribute (string $name)
String $name: Name of the property to be deleted
15. Get Properties
string Domelement::getattribute (String $name)
String $name: Property name of the property value to get

DOMDocument is also part of the DOM extension PHP5, which can be used to build or parse html/xml, and only UTF-8 encoding is currently supported.

The code is as follows Copy Code

$xmlstring = <<<xml
<?xml version= ' 1.0 '?>
<document>
<cmd attr= ' default ' >login</cmd>
<login>imdonkey</login>
</document>
XML;

$dom = new DOMDocument ();
$dom->loadxml ($xmlstring);
Print_r (GetArray ($dom->documentelement));

function GetArray ($node) {
$array = false;

if ($node->hasattributes ()) {
foreach ($node->attributes as $attr) {
$array [$attr->nodename] = $attr->nodevalue;
}
}

if ($node->haschildnodes ()) {
if ($node->childnodes->length = = 1) {
$array [$node->firstchild->nodename] = GetArray ($node->firstchild);
} else {
foreach ($node->childnodes as $childNode) {
if ($childNode->nodetype!= xml_text_node) {
$array [$childNode->nodename][] = GetArray ($childNode);
}
}
}
} else {
return $node->nodevalue;
}
return $array;
}

SimpleXML

SimpleXML is a set of Easy-to-use XML toolset that PHP5 provides to convert XML into an easily processed object or to organize the generation of XML data. However, it does not apply to XML that contains namespace, but also to ensure that the XML is well-formed (well-formed). It provides three methods: Simplexml_import_dom, Simplexml_load_file, simplexml_load_string, and the function name is a straightforward illustration of the function. All three functions return the SimpleXMLElement object, and the data is read/added through the SimpleXMLElement action

The code is as follows Copy Code


$string = <<<xml
<?xml version= ' 1.0 '?>
<document>
<cmd>login</cmd>
<login>imdonkey</login>
</document>
XML;

$xml = simplexml_load_string ($string);
Print_r ($xml);
$login = $xml->login;//returned here is still a SimpleXMLElement object.
Print_r ($login);
$login = (string) $xml->login;//when doing a data comparison, be aware that you want to cast first
Print_r ($login);

The advantage of SimpleXML is that it is simple to develop, with the disadvantage that it will load the entire XML into memory and then process it, so it may not be able to parse the XML document for the hyper-content. If you are reading a small file, and the XML does not contain namespace, then SimpleXML is a good choice.


XMLReader

XmlReader is also an extension after PHP5 (installed by default after 5.1), which moves in the document flow like a cursor and stops at each node, and is flexible to operate. It provides fast and non cached streaming access to input, can read streams or documents, allows users to extract data from them, and skips records that have no meaning to the application.
Using a Google weather API to get information about the use of XmlReader, here is only a small part of the function, more also refer to the official documentation.

The code is as follows Copy Code

$xml _uri = ' HTTP://WWW.GOOGLE.COM/IG/API?WEATHER=BEIJING&HL=ZH-CN ';
$current = Array ();
$forecast = Array ();

$reader = new XMLReader ();
$reader->open ($xml _uri, ' GBK ');
while ($reader->read ()) {
 //get current Data
  if ($reader->name = = "Current_conditions" &A mp;& $reader->nodetype = = xmlreader::element) {
    while ($reader->read () && $ Reader->name!= "Current_conditions") {
      $name = $reader->name;
       $value = $reader->getattribute (' data ');
      $current [$name] = $value;
   }
 }

Get Forecast data
if ($reader->name = = "Forecast_conditions" && $reader->nodetype = = xmlreader::element) {
$sub _forecast = Array ();
while ($reader->read () && $reader->name!= "Forecast_conditions") {
$name = $reader->name;
$value = $reader->getattribute (' data ');
$sub _forecast[$name] = $value;
}
$forecast [] = $sub _forecast;
}
}
$reader->close ();

XmlReader is similar to XML parser, which is a side-reading operation, the big difference being that the SAX model is a "push" model in which the parser pushes events to the application and notifies the application each time a new node is read. Applications using XmlReader can extract nodes from the reader at will, and the control is better.
Because XmlReader is based on libxml, some functions refer to the documentation to see if it applies to your libxml version.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.