Current Location: Home> Latest Articles> How to use xml_parse and PDO to parse XML data in a database

How to use xml_parse and PDO to parse XML data in a database

M66 2025-04-26

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.

Step 1: Prepare XML data in the database

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>');

Step 2: Use PDO to read XML data from the database

 <?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();
}
?>

Step 3: Use xml_parse to parse XML data

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

Step 4: Output sample results

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