3v4l.org

run code in 300+ PHP versions simultaneously
<?php // First of all, I've added <root> element to your XML document, // because otherwise it's invalid. // But it's not important for the rest of the code. // // Also I've added additional <somethingelse> tag to show that filtering is working $xmlString = '<root><details> <name>name1</name> <address>address1</address> </details> <details> <name>name2</name> <mobile>mobileNum</mobile> <address>address2</address> <somethingelse>This will be filtered</somethingelse> </details></root>'; $xml = new SimpleXMLElement($xmlString); //array_flip to get node names as keys for later foreach loop $nodes = array_flip(array ( 'person_name' => 'name', 'mobile_no' => 'mobile', 'address' => 'address', )); $final_data = array(); //Here are all <details> sections' data in array. $node_values = $xml->xpath('//details'); $node_values = json_decode(json_encode((array)$node_values), TRUE); //this loop filters XML data from keys not existing in $nodes, which are the only that you want to keep foreach($node_values as $node) { $final_data[] = array_intersect_key($node, $nodes); } var_dump($final_data);
Output for 7.0.0 - 7.0.20, 7.1.0 - 7.1.7, 7.2.29 - 7.2.33, 7.3.16 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.28, 8.2.0 - 8.2.18, 8.3.0 - 8.3.4, 8.3.6
array(2) { [0]=> array(2) { ["name"]=> string(5) "name1" ["address"]=> string(8) "address1" } [1]=> array(3) { ["name"]=> string(5) "name2" ["mobile"]=> string(9) "mobileNum" ["address"]=> string(8) "address2" } }
Output for 8.3.5
Warning: PHP Startup: Unable to load dynamic library 'sodium.so' (tried: /usr/lib/php/8.3.5/modules/sodium.so (libsodium.so.23: cannot open shared object file: No such file or directory), /usr/lib/php/8.3.5/modules/sodium.so.so (/usr/lib/php/8.3.5/modules/sodium.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 array(2) { [0]=> array(2) { ["name"]=> string(5) "name1" ["address"]=> string(8) "address1" } [1]=> array(3) { ["name"]=> string(5) "name2" ["mobile"]=> string(9) "mobileNum" ["address"]=> string(8) "address2" } }

preferences:
179.57 ms | 402 KiB | 163 Q