Skip to content

Instantly share code, notes, and snippets.

@gwarnants
Created February 11, 2016 14:00
Show Gist options
  • Save gwarnants/59e7d0707c75b95ab012 to your computer and use it in GitHub Desktop.
Save gwarnants/59e7d0707c75b95ab012 to your computer and use it in GitHub Desktop.
Parse XML with namespaces using SimpleXML
<?php
$xml = <<<ENDXML
<catalog xmlns:ns1="http://localhost/ns1" xmlns:ns2="http://localhost/ns2">
<product id="1" ns2:order="2">
<name>Test</name>
<ns1:price>100</ns1:price>
</product>
</catalog>
ENDXML;
foreach (simplexml_load_string($xml)->product as $product) {
echo (string)$product->name, // child
(string)$product->children('ns1', true)->price, // namespaced child
(string)$product['id'], // attribute
(string)$product->attributes('ns2', true)->order; // namespaced attribute
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment