Current Location: Home> Latest Articles> How to use XML data parsed by xml_parse with array_map

How to use XML data parsed by xml_parse with array_map

M66 2025-04-24

In PHP, processing XML data is a common task, especially when interacting with external systems. xml_parse is an underlying parsing function, while array_map is a higher-order function for batch data conversion. Combining these two functions can effectively process and convert batch XML data, improving the readability and maintainability of the code.

Below we will use an example to demonstrate how to achieve this goal.

Example: Batch processing of XML data and converting it into a structured array

Let's start with a simple XML text:

 <items>
    <item>
        <id>1</id>
        <name>merchandiseA</name>
        <url>http://m66.net/product/1</url>
    </item>
    <item>
        <id>2</id>
        <name>merchandiseB</name>
        <url>http://m66.net/product/2</url>
    </item>
</items>

Step 1: Use xml_parser to parse XML

 $xmlData = <<<XML
<items>
    <item>
        <id>1</id>
        <name>merchandiseA</name>
        <url>http://m66.net/product/1</url>
    </item>
    <item>
        <id>2</id>
        <name>merchandiseB</name>
        <url>http://m66.net/product/2</url>
    </item>
</items>
XML;

$parser = xml_parser_create();
xml_parse_into_struct($parser, $xmlData, $values, $index);
xml_parser_free($parser);

This parses the XML data into two arrays: $values ​​(including details for all tags) and $index (including index locations for tags).

Step 2: Extract the item element

 $items = [];
foreach ($index['ITEM'] as $i => $pos) {
    $item = [];

    $idPos = $index['ID'][$i];
    $namePos = $index['NAME'][$i];
    $urlPos = $index['URL'][$i];

    $item['id'] = $values[$idPos]['value'];
    $item['name'] = $values[$namePos]['value'];
    $item['url'] = $values[$urlPos]['value'];

    $items[] = $item;
}

Now we get a neat array structure, for example:

 [
    ['id' => '1', 'name' => 'merchandiseA', 'url' => 'http://m66.net/product/1'],
    ['id' => '2', 'name' => 'merchandiseB', 'url' => 'http://m66.net/product/2'],
]

Step 3: Use array_map to convert data in batches

Suppose we want to add ?ref=xml parameter to each URL and convert the product name to capitalization, we can do this:

 $processedItems = array_map(function($item) {
    $item['name'] = strtoupper($item['name']);
    $item['url'] .= '?ref=xml';
    return $item;
}, $items);

Final output:

 print_r($processedItems);

Output result:

 Array
(
    [0] => Array
        (
            [id] => 1
            [name] => merchandiseA
            [url] => http://m66.net/product/1?ref=xml
        )

    [1] => Array
        (
            [id] => 2
            [name] => merchandiseB
            [url] => http://m66.net/product/2?ref=xml
        )
)