In modern web applications, the diversity of data formats makes developers often need to process XML data. If the XML data is stored in the database, we can use PHP's xml_parse function and PDO database operations to achieve automatic parsing and processing. This article will introduce this process in detail and include runnable code examples.
Suppose we have a MySQL database with a table named xml_data , and the structure is as follows:
CREATE TABLE xml_data (
id INT AUTO_INCREMENT PRIMARY KEY,
xml_content TEXT NOT NULL
);
Let's insert an XML data as an example:
INSERT INTO xml_data (xml_content) VALUES
('<book><title>PHP Programming practice</title><author>Zhang San</author><url>https://m66.net/books/php</url></book>');
<?php
$dsn = 'mysql:host=localhost;dbname=test_db;charset=utf8mb4';
$username = 'db_user';
$password = 'db_pass';
try {
$pdo = new PDO($dsn, $username, $password);
$stmt = $pdo->query("SELECT xml_content FROM xml_data");
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$xml = $row['xml_content'];
parseXmlWithHandler($xml);
}
} catch (PDOException $e) {
echo "Database connection failed: " . $e->getMessage();
}
?>
PHP's xml_parse is an event-driven parser. Before use, you need to define the parsing function and processor:
function parseXmlWithHandler($xmlString) {
$parser = xml_parser_create();
xml_set_element_handler($parser, "startElement", "endElement");
xml_set_character_data_handler($parser, "characterData");
if (!xml_parse($parser, $xmlString, true)) {
echo "XML Parsing error: " . xml_error_string(xml_get_error_code($parser));
return;
}
xml_parser_free($parser);
}
function startElement($parser, $name, $attrs) {
echo "<b>Start tag:</b> $name<br>";
}
function endElement($parser, $name) {
echo "<b>End tag:</b> $name<br>";
}
function characterData($parser, $data) {
$trimmed = trim($data);
if ($trimmed !== '') {
echo "<b>content:</b> $trimmed<br>";
}
}
After running the above script, the output will be similar to:
Start tag:BOOK
Start tag:TITLE
content:PHP Programming practice
End tag:TITLE
Start tag:AUTHOR
content:Zhang San
End tag:AUTHOR
Start tag:URL
content:https://m66.net/books/php
End tag:URL
End tag:BOOK