Home >Backend Development >PHP Tutorial >Analysis of various methods of PHP XML operation (more detailed)_PHP tutorial

Analysis of various methods of PHP XML operation (more detailed)_PHP tutorial

WBOY
WBOYOriginal
2016-07-21 15:36:10867browse

XML is a popular semi-structured file format that stores data in a database-like format. In practical applications, some simple and low-security data are often stored in XML file format. The advantage of this is that on the one hand, it can improve reading efficiency by reducing interactive operations with the database, and on the other hand, it can effectively utilize the advantages of XML to reduce the difficulty of program writing.
PHP provides a complete set of methods for reading XML files, making it easy to write XML-based scripts. This chapter will introduce the operation methods of PHP and XML, and give a brief introduction to several commonly used XML class libraries.
1 Introduction to XML
XML is the abbreviation of "eXtensible Markup Language" and is a markup language similar to HTML. But unlike HTML, XML is mainly used to describe data and store data, while HTML is mainly used to display data.
XML is a "meta tag" language that allows developers to create tag names according to their needs. For example, the following XML code can be used to describe a message.

Copy code The code is as follows:


Welcome
Simon
Welcome to XML guestbook!!


Where, tags mark this as a message. There is a title, author, and content in the message, which completely expresses a message message.
At the top of an XML file, is usually used to identify the beginning of XML data and XML data uses standard version information. When you access an XML file in a browser, you can see clearly structured XML data information, as shown in Figure 1.
'700')this. style="max-width:90%";" border="0">
XML is developing very rapidly. In recent years, many software developers have begun to adopt XML development standards for application development, and many emerging technologies are based on XML data, which means that XML will become an integral part of Web technology.
2 Simple XML operation
In practical applications, the interaction between PHP and XML is very widely used. The SimpleXML component is a newly added simple XML operation component in PHP5. Compared with the traditional XML component, , the use of the SimpleXML component is very simple. This section will give a detailed introduction to the method of using the
SimpleXML component to manipulate XML.
2.1 Create a SimpleXML object
SimpleXML object is a temporary variable used to temporarily store XML data. , the operations on XML are completed by operating SimpleXML objects. The SimpleXML component provides two methods for creating SimpleXML objects. The first method is to use the simplexml_load_string function to read the XML data in a string variable to complete the creation. The syntax format is as follows.
simplexml_load_string(string data)
The data variable here is used to store XML data. The following code uses the simplexml_load_string function to create a SimpleXML object

Copy code The code is as follows:

$data = <<


production support


100001
Simon
24
1982-11-06
5000.00
1000.00


100002
Elaine
24
1982-01-01
6000.00
2000.00




testing center


110001
Helen
23
1983-07-21
5000.00
1000.00




XML;
$xml = simplexml_load_string($data); //创建 SimpleXML对象
print_r($xml); //输出 XML
?>

在上面的例子中,$data变量存储了一段 XML数据。 simplexml_load_string函数将变量$data转化成 SimpleXML对象。通过 print_r函数的输出可以看出该对象的结构,运行结果如下所示。
复制代码 代码如下:

SimpleXMLElement Object
(
[depart] => Array
(
[0] => SimpleXMLElement Object
(
[name] => production support
[employees] => SimpleXMLElement Object
( [employee] => Array (
[0] => SimpleXMLElement Object
( [serial_no] => 100001
[name] => Simon
[age] => 24
[birthday] => 1982-11-06
[salary] => 5000.00
[bonus] => 1000.00
)
[1] => SimpleXMLElement Object
( [serial_no] => 100002
[name] => Elaine
[age] => 24
[birthday] => 1982-01-01
[salary] => 6000.00
[bonus] => 2000.00
)
)
)
)
[1] => SimpleXMLElement Object
(
[name] => testing center
[employees] => SimpleXMLElement Object
(
[employee] => SimpleXMLElement Object
(
[serial_no] => 110001
[name] => Helen
[age] => 23
[birthday] => 1983-07-21
[salary] => 5000.00
[bonus] => 1000.00
)
)
)
)
)

从输出结果可以看出,SimpleXML对象的结构与 XML数据的格式完全相同。
第二种方法是使用 simplexml_load_flie函数读取一个 XML文件来完成创建的,其语法格式如下所示。
simplexml_load_file(string filename)
这里的 filename变量是用于存储 XML数据文件的文件名及其所在路径。以下代码使用 simplexml_load_file函数来创建了一个 SimpleXML对象。
复制代码 代码如下:

$xml = simplexml_load_file('example.xml'); //创建 SimpleXML对象
print_r($xml); //输出 XML
?>

Among them, the data stored in example.xml is exactly the same as the $data above, and the running results are exactly the same as above.
The above two methods implement the same function, the difference lies in the different data sources of XML. If the XML data source is in a PHP script file, you need to use simplexml_load_string to create it. If the XML data source is in a separate XML file, you need to use simplexml_load_file to create it.
2.2 Reading XML data in SimpleXML objects
Previously we introduced the use of the print_r function to read data in SimpleXML objects, and the return result is similar to the structure of an array. Obviously, this display method is undesirable in practical applications. Here we will introduce several other methods of reading XML data in SimpleXML objects.
1. The var_dump function displays object detailed information
The var_dump function can be used to display detailed information of SimpleXML objects. Compared with the print_r function, the var_dump function displays more complete information. Its syntax is as follows.
void var_dump(object1, object2 … )
The following code uses the var_dump function to output the detailed information of the object in the above example.
Copy code The code is as follows:



The running results are as follows.
Copy code The code is as follows:

object(SimpleXMLElement)#1 (1) { ["depart"]=> array(2) {
[0]=>
object(SimpleXMLElement)#2 (2) {
["name"]=>
string(18) “production support”
["employees"]=>
object(SimpleXMLElement)#4 (1) {
["employee"]=>
array(2) {
[0]=> ;
object(SimpleXMLElement)#5 (6) {
["serial_no"]=>
string(6) “100001″
["name"]=>
string (5) “Simon”
["age"]=>
string(2) “24″
["birthday"]=>
string(10) “1982-11- 06″
["salary"]=>
string(7) “5000.00″
["bonus"]=>
string(7) “1000.00″
}
[1]=>
object(SimpleXMLElement)#6 (6) {
["serial_no"]=>
string(6) “100002″
["name"]= >
string(6) “Elaine”
["age"]=>
string(2) “24″
["birthday"]=>
string(10 ) “1982-01-01″
["salary"]=>
string(7) “6000.00″
["bonus"]=>
string(7) “2000.00″
}
}
}
}
[1]=>
object(SimpleXMLElement)#3 (2) {
["name"]=>
string(14) “testing center”
["employees"]=>
object(SimpleXMLElement)#7 (1) {
["employee"]=>
object( SimpleXMLElement)#8 (6) {
["serial_no"]=>
string(6) “110001″
["name"]=>
string(5) “Helen”
["age"]=>
string(2) “23″
["birthday"]=>
string(10) “1983-07-21″
[ "salary"]=>
string(7) “5000.00″
["bonus"]=>
string(7) “1000.00″
}}}}}

Compared with the results output by print_r previously, the structure of the output results of the var_dump function is more rigorous, and the data type of each attribute in the object is analyzed. In practical applications, the var_dump function is often used for object detection during program debugging.
2. Reading the tag
in XML data is similar to operating variables of array type, and reading XML can also be done in a similar way. For example, if you need to read the "name" attribute under each "depart" tag in the above XML data, you can do it by using the foreach function, as shown in the following code
.
Copy code The code is as follows:

depart as $a)
{
echo “$a->name
”;
}
?>

The running results are as follows.
production support
testing center
//Read XML file//Loop through each part tag in the XML data
//Output the name attribute
You can also use square brackets "[]" to directly read the specified tag in the XML data. The following code outputs the "name" attribute of the first "depart" tag in the XML data above.
Copy code The code is as follows:

$xml = simplexml_load_file('example.xml') ; //Read XML file
echo $xml->depart->name[0]; //Output node
?>

The running results are as follows.
production support
For all child tags under a tag, the SimpleXML component provides the children method to read. For example, for the "depart" tag in the XML data above, there are two sub-tags under it: "name" and "employees". The following code implements reading the subtags under the first "depart" tag.
Copy code The code is as follows:

$xml = simplexml_load_file('example.xml') ;
foreach ($xml->depart->children() as $depart) //Loop to read the sub-tags under the depart tag
{
var_dump($depart); //Output tags The XML data
}
?>

The running results are as follows.
Copy code The code is as follows:

object(SimpleXMLElement)#3 (1) {
[0]=> ;
string(18) “production support”
}
object(SimpleXMLElement)#5 (1) {
["employee"]=>
array(2) {
[0]=>
object(SimpleXMLElement)#3 (6) {
["serial_no"]=>
string(6) “100001″
["name"]= >
string(5) “Simon”
["age"]=>
string(2) “24″
["birthday"]=>
string(10 ) “1982-11-06″
["salary"]=>
string(7) “5000.00″
["bonus"]=>
string(7) “1000.00″
}
[1]=>
object(SimpleXMLElement)#6 (6) {
["serial_no"]=>
string(6) “100002″
["name"]=>
string(6) “Elaine”
["age"]=>
string(2) “24″
["birthday"]=>
string(10) “1982-01-01″
["salary"]=>
string(7) “6000.00″
["bonus"]=>
string (7) “2000.00″
}
}
}

It can be seen that after using the children method, all child tags are treated as a new XML file. deal with.
3. Query based on XML data path
SimpleXML component provides a query method based on XML data path. The XML data path is all the tags that pass from the root of XML to a certain tag. This path uses slashes "/" to separate tag names. For example, for the above XML data, if you want to query the values ​​​​in all tags "name", starting from the root and going through the departments, department, employees and employees tags, the path
is "/departs/depart/employees/employee /name". The SimpleXML component uses the xpath method to parse paths, and its syntax format is as follows.
xpath(string path)
where path is the path. This method returns an array containing all tag values ​​to be queried. The following code queries all name tags in the above XML data.
Copy code The code is as follows:

$xml = simplexml_load_file('example.xml') ; //Read XML file
$result = $xml->xpath('/departs/depart/employees/employee/name'); //Define node
var_dump($result); //Output The running results of node
?>

are as follows.
Copy code The code is as follows:

array(3) {
[0]=> object(SimpleXMLElement) #2 (1) {
[0]=> string(5) “Simon”
}
[1]=> object(SimpleXMLElement)#3 (1) {
[0 ]=> string(6) “Elaine”
}
[2]=> object(SimpleXMLElement)#4 (1) {
[0]=> string(5) “Helen”
}
}

It can be seen that all name tags are queried.
2.3 Modification of XML data
The modification of XML data is similar to the method of reading tags in XML data. That is, by directly modifying the value of the tag in the SimpleXML object. The following code implements the modification of the "name" sub-tag of the first "depart" tag in the XML data above.
Copy code The code is as follows:

$xml = simplexml_load_file('example.xml') ; //Read XML
$xml->depart->name[0] = "Human Resource"; //Modify node
?>

After modification, It will not have any impact on XML files. However, in the program, the modified value will be used for reading the SimpleXML object.
2.4 Standardizing XML data
SimpleXML also provides a method of standardizing XML data asXML. The asXML method can effectively rearrange the content in the SimpleXML object according to the XML 1.0 standard and return it as a string data type. The following code implements the standardization of the above XML data.
Copy code The code is as follows:

$xml = simplexml_load_file('example.xml'); //Read XML data
echo $xml->asXML(); //Standardize XML data
?>

2.5 Storage of XML data
The method of storing XML data in a SimpleXML object into an XML file is very simple, that is, outputting the return result of the asXML method to a file That’s it. The following code first modifies the depart name in the XML file, and then outputs the modified XML data to another XML file.
Copy code The code is as follows:

$xml = simplexml_load_file('example.xml') ; //Read XML data
$newxml = $xml->asXML(); //Standardize XML data
$fp = fopen("newxml.xml", "w"); //Open to Write XML data to the file
fwrite($fp, $newxml); //Write XML data
fclose($fp); //Close the file
?>

After the code is run, you can see the XML data in the newxml.xml file as shown below.
It can be seen that the modifications to the XML file have been saved in the output file.
3 Dynamic creation of XML documents
In practical applications, it is sometimes necessary to dynamically generate XML documents. The SimpleXML component introduced earlier does not provide a method for creating XML documents. Therefore, if you need to dynamically create an XML document, you often use DOM components to create it. DOM is the abbreviation of Document Object Model. The DOM component provides a tree parsing mode for XML documents. The following code creates an XML document using DOM components.

Copy code The code is as follows:

//Create a new DOM document
$dom = new DomDocument();
//Create the departments tag at the root node
$departs = $dom->createElement('departs');
$dom->appendChild( $departs);
//Create depart sub-tag under the departments tag
$depart = $dom->createElement('depart');
$departs->appendChild($depart);
//Create employees sub-tag under the depart tag
$employees = $dom->createElement('employees');
$depart->appendChild($employees);
//In Create employee sub-tag under employees tag
$employee = $dom->createElement('employee');
$employees->appendChild($employee);
//Create serial_no under employee tag Child tag
$serial_no = $dom->createElement('serial_no');
$employee->appendChild($serial_no);
//Add value node 100001 for the serial_no tag
$ serial_no_value = $dom->createTextNode('100001′);
$serial_no->appendChild($serial_no_value);
//Output XML data
echo $dom->saveXML();
?>
The output results are as follows.





100001





In addition to In addition to dynamically creating XML documents, it can also be used to read XML files. The following code implements reading of the previous
XML file.
Copy code The code is as follows:

$dom = new DomDocument(); //Create DOM object
$dom->load('example.xml'); //Read XML file
$root = $dom->documentElement; //Get the root of XML data
read_child( $root); //Call the read_child function to read the root object
function read_child($node)
{
$children = $node->childNodes; //Get all child nodes of $node
foreach($children as $e) //Loop to read each child node
{
if($e->nodeType == XML_TEXT_NODE) ​​//If the child node is text type, output
{
echo $e->nodeValue.”
”;
}
else if($e->nodeType == XML_ELEMENT_NODE) ​​//If the child node is a node object, call Function processing
{
read_child($e);
}
}
}
?>

The running results are as follows.
Copy code The code is as follows:

Quote
production support
100001
Simon
24
1982-11-06
5000.00
1000.00
100002
Elaine
24
1982-01-01
6000.00
2000.00
testing center
110001
Helen
23
1983-07-21
5000.00
1000.00

The above example uses a recursive method to process XML data and realizes the function of outputting all text tags in XML data.
4 XML application example - guestbook
The basic operations of XML have been introduced before. This section will take designing an XML guestbook as an example to explain in detail how to realize the interactive operation of PHP and XML data in practical applications.
4.1 XML file structure design
XML files are used to store XML data, which is the messages in the guestbook. Here, for each message, the XML data mainly includes three contents: message title, message author's name, and message content. Therefore, the format of the XML file is designed as follows.

Copy code The code is as follows:




This is the title of the message
This is the person who left the message




4.2 Writing the submission page
The submission message page consists of two pages composition. One is an HTML file for a form that allows visitors to write messages, and the other is a PHP script used to process visitor input. The HTML code for the form is shown below.
Copy code The code is as follows:



Post a new comment


< body>

Post a new message
















title
Author
Content < textarea name=”content” cols=”50″ rows=”10″ id=”content”>









For PHP scripts used to process user input, the The basic logic is to first create a DOM object, then read the XML data in the XML file, then create new nodes on the XML object and store the user's input, and finally output the XML data to the original XML file. The specific implementation code is as follows.
Copy code The code is as follows:

$guestbook = new DomDocument(); //Create A new DOM object
$guestbook->load('DB/guestbook.xml'); //Read XML data
$threads = $guestbook->documentElement; //Get the root of the XML structure
//Create a new thread node
$thread = $guestbook->createElement('thread');
$threads->appendChild($thread);
//In the new Create the title tag on the thread node
$title = $guestbook->createElement('title');
$title->appendChild($guestbook->createTextNode($_POST['title'])) ;
$thread->appendChild($title);
//Create the author tag on the new thread node
$author = $guestbook->createElement('author');
$author->appendChild($guestbook->createTextNode($_POST['author']));
$thread->appendChild($author);
//Create on new thread node content tag
$content = $guestbook->createElement('content');
$content->appendChild($guestbook->createTextNode($_POST['content']));
$thread->appendChild($content);
//Write XML data to the file
$fp = fopen("DB/guestbook.xml", "w");
if(fwrite( $fp, $guestbook->saveXML()))
echo “The message was submitted successfully”;
else
echo “The message was submitted failed”;
fclose($fp);
? >

Run the above HTML file in the browser and fill in the appropriate message content, as shown in Figure 2.
'700')this. style="max-width:90%";" border="0">
Figure 2 New message interface
After clicking the [Submit] button, the content in the XML file is as follows.
You can see that the message has been stored in the XML file.
The display page is ready. It is easy to implement using the SimpleXML component introduced earlier. The specific implementation code is as follows:

Copy code The code is as follows: //Open the XML file used to store messages
$guestbook = simplexml_load_file('DB/guestbook.xml');
foreach($guestbook->thread as $th) / /Loop to read each thread tag in the XML data
{
echo "Title: ".$th->title."
";
echo “Author: ”.$th->author.”
”;
echo “Content:
 ".$th->content."
";
echo "
";
}
?>



View the running results in the browser as shown in Figure 3.

'700')this.width='700';if(this.offsetHeight>'700')this.height='700';" border=0>


www.bkjia.com
http: //www.bkjia.com/PHPjc/322160.htmlTechArticleXML is a popular semi-structured file format that stores data in a database-like format. In practical applications, some simple and low-security data often use XML files...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn