Home > Article > Backend Development > Example of using SimpleXML to parse and process HTML/XML in PHP
Example of parsing and processing HTML/XML using SimpleXML in PHP
Introduction:
SimpleXML is a powerful and easy-to-use extension in PHP for parsing and processing HTML or XML documents. It provides a concise way to access and manipulate the elements and properties of a document. This article will introduce how to use SimpleXML to parse and process HTML or XML documents in PHP, and provide some practical code examples.
$xmlString = '<?xml version="1.0" encoding="UTF-8"?> <books> <book> <title>PHP 7 in Practice</title> <author>John Smith</author> <price>29.99</price> </book> <book> <title>JavaScript: The Good Parts</title> <author>Douglas Crockford</author> <price>19.99</price> </book> </books>'; $xml = simplexml_load_string($xmlString);
The above code parses a simple XML document containing information about two books into a SimpleXMLElement object $xml.
echo "第一本书的标题:" . $xml->book[0]->title . " "; echo "第一本书的作者:" . $xml->book[0]->author . " "; echo "第一本书的价格:" . $xml->book[0]->price . " "; echo "第二本书的标题:" . $xml->book[1]->title . " "; echo "第二本书的作者:" . $xml->book[1]->author . " "; echo "第二本书的价格:" . $xml->book[1]->price . " ";
The above code outputs the title, author and price information of the two books in the XML document.
foreach ($xml->book as $book) { echo "书名:" . $book->title . " "; echo "作者:" . $book->author . " "; echo "价格:" . $book->price . " "; }
The above code outputs the information of each book in the XML document in turn.
$htmlString = '<html> <body> <h1>Hello, World!</h1> <p>This is a paragraph.</p> </body> </html>'; $html = simplexml_load_string($htmlString); echo "页面标题:" . $html->body->h1 . " "; echo "段落内容:" . $html->body->p . " ";
The above code parses the HTML document into a SimpleXMLElement object $html, and outputs the page title and paragraph content.
Summary:
Using SimpleXML to parse and process HTML or XML documents can greatly simplify the process of operating documents in PHP. This article explains how to use SimpleXML to parse and process HTML or XML documents, and provides some practical code examples. I hope this article can help you better understand and use SimpleXML extensions.
The above are only the basic usage of SimpleXML. SimpleXML also provides many advanced functions and methods, such as document filtering, namespace support, etc. You can refer to PHP official documentation or online resources to learn more.
The above is the detailed content of Example of using SimpleXML to parse and process HTML/XML in PHP. For more information, please follow other related articles on the PHP Chinese website!