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.
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>
$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).
$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'],
]
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
)
)