Summary of xml reading methods for PHP

Source: Internet
Author: User
The xml (ExtensibleMarkupLanguage) method for PHP to read and operate XML can be used to expand the markup language. it has many purposes and can be used to store data and exchange data, prompt data for many types of applications. During web development, programs are often used to read xml data and parse the data. Below we will summarize various methods for php to read and operate xml. There are four common methods for php to read and parse xml: Xmlparser and Simp PHP to read and operate xml.

XML (Extensible Markup Language) can be used to expand the Markup Language. it can be used to store data, exchange data, and prompt data for many applications.

During web development, programs are often used to read xml data and parse the data.

Below we will summarize various methods for php to read and operate xml.

Php provides four common methods for reading and parsing xml: Xml parser, SimpleXML, XMLReader, and DOMDocument. The following describes these methods respectively.

(1) Xml parseXML Parser uses the Expat XML Parser. Expat is an event-based parser that treats XML documents as a series of events. When an event occurs, it calls a specified function to process it. Expat is an unverified parser that ignores any DTD linked to the document.

However, if the document format is not good, it will end with an error message. Because it is event-based and does not validate, Expat is fast and suitable for web applications. Therefore, it has good performance because it does not load the entire xml file into the memory and then process it, but parse and process it. However, because of this, it is not suitable for those who need to dynamically adjust the xml structure or perform complex operations based on the xml context structure.

If you only want to parse and process a well-structured xml document, it can well complete the task. Note that XML Parser only supports three encoding formats: US-ASCII, ISO-8859-1, and UTF-8. if your xml data is other encoding, you need to first convert it to one of the three.

There are two common parsing methods for XML Parser (actually two functions): xml_parse_into_struct and xml_set_element_handler. Because XML Parser supports PHP4, it is applicable to systems of earlier versions. So here we will not make a profound explanation.

For the PHP5 environment, we recommend that you consider the following three methods as much as possible.

(2) DOMDocumentDOMDocument is part of the DOM extension launched after PHP5. it can be used to establish or parse html/xml. Currently, only UTF-8 encoding is supported.

Here is an example to illustrate how php reads xml through DOMDocument.

$xmlstring=<<
 
 

login
imdonkey

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;
}

From the program, we can see that DOMDocument loads xml into the memory at a time, so pay attention to memory problems.

(3) XMLReaderXMLReader is also an extension after PHP5 (installed by default after PHP5.1). It moves in the document stream just like a cursor and stops at each node. it is flexible to operate.

It provides fast and non-cache stream access to the input, and can read streams or documents, allowing users to extract data from it and skip records that are meaningless to the application.

The following example shows how to use XMLReader to obtain google Weather api information using php. this example only involves a small number of functions. For more information, see the official documentation.

$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" && $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();

Similar to XML Parser, XMLReader and XML Parser are both read-side operations. The big difference is that the SAX model is a "push" model, where the analyzer pushes events to the application, the application is notified every time a new node is read. the XmlReader application can extract nodes from the reader at will, which is more controllable.

Because XMLReader is based on libxml, you need to refer to the documentation to see if it is applicable to your libxml version.

(4) SimpleXMLSimpleXML is also a set of easy-to-use xml tools provided after PHP5. it can convert xml into easy-to-process objects and organize and generate xml data. However, it does not apply to xml containing namespace (namespace), and must ensure that the xml format is complete (well-formed ).

It provides three methods: simplexml_import_dom, simplexml_load_file, and simplexml_load_string. these three function names intuitively demonstrate their functions. All three functions return SimpleXMLElement objects, and data reading/adding is performed through SimpleXMLElement.

Example:

$ String = <
 
 

Login
Imdonkey

XML; $ xml = simplexml_load_string ($ string );
Print_r ($ xml );
$ Login = $ xml-> login; // The Returned result is still a SimpleXMLElement object.
Print_r ($ login );
$ Login = (string) $ xml-> login; // when comparing data, be sure to forcibly convert
Print_r ($ login );

SimpleXML is easy to develop, but it also loads the entire xml into the memory before processing. Therefore, it may not be able to resolve xml documents with too much content.

If you want to read small files and xml does not contain namespace, SimpleXML is a good choice.

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.