I need faster way to parse XML to array (without empty values).
Till now I was parsing XML to array using Array2XML (by Lalit Patel) library, but it was bottleneck to script. I was looking to speed up it and found about 15x faster way:
class SimpleXmlDecoder
{
public function decode(string $xml): array
{
try {
$decoded = json_decode(json_encode(
simplexml_load_string($xml, "SimpleXMLElement", LIBXML_NOCDATA)
),TRUE);
if (empty($decoded)) {
return [];
}
return self::mapEmptyArraysElementsToEmptyString($decoded);
} catch (\Exception $exception) {
return [];
}
}
private static function mapEmptyArraysElementsToEmptyString($array): array
{
return array_map(
static function($value) {
if (!is_array($value)) {
return $value;
}
if (empty($value)) {
return '';
}
return self::mapEmptyArraysElementsToEmptyString($value);
},
$array
);
}
}
It is enough now, but can be bottleneck in future. Do you know faster way to do it?
@Edit Size of every XML: 100kB-1MB Need return values from ALL NON-EMPTY elements with name and value.