Trick: Use XPath in PHP with XML that contains default namespace (xmlns)

If your XML has default name space like:
    <COLLADA xmlns=”http://www.collada.org/2005/11/COLLADASchema”></COLLADA&gt;
Then to use DOMXpath you should register this namespace with some prefix like:
    $xpath->registerNameSpace(‘dp’, ‘http://www.collada.org/2005/11/COLLADASchema&#8217;);
here ‘dp’ means default prefix;
Then use this prefix in your XPath query like:
    $nodes = $xpath->query(‘//fp:COLLADA’);

// real example
$DOMDocument = new DOMDocument;
$DOMDocument->strictErrorChecking = false;
//$sXml = ‘<COLLADA xmlns=”http://www.collada.org/2005/11/COLLADASchema”></COLLADA>&#8217;;
if (! $DOMDocument->loadXML($sXml))
    _error(“can’t parse XML”);

$xpath = new DOMXpath($DOMDocument);
$xpath->registerNameSpace(‘dp’, ‘http://www.collada.org/2005/11/COLLADASchema&#8217;);

foreach ($xpath->query(‘//dp:image/dp:init_from’) as $node)
{
    $node->nodeValue = $dir . “/model.jpg”;
}

$sXml = $DOMDocument->saveXML();

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: