Hi, i'm trying to parse my XML string into a simplexml object and later retrieve it through xpath function.

In the example below, only xmlns with name "http://google.com/API/XSD/SearchQ.xsd" is used when calling getNamespaces() to check.

Since it didn't have any name, i had to register it with registerXPathNamespace() for it to work.

My question is..is it possible to use xpath without registering the namespace, even if xmlns="http://google.com/API/XSD/SearchQ.xsd" is used ?

<html>
<body>
<?php

$xdata = "<?xml version=\"1.0\" encoding=\"utf-8\"?>".
         //"<SearchRecords xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns=\"http://google.com/API/XSD/SearchQ.xsd\">".
		 "<SearchRecords xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">".
		 "<SearchParameters>".
			"<Parameter>".
			"<Name>lastname</Name>".
			"<Value>Goober</Value>".
			"</Parameter>".
			"<Parameter>".
			"<Name>firstname</Name>".
			"<Value>Snazzy</Value>".
			"</Parameter>".
		  "</SearchParameters>".
		  "</SearchRecords>";

$xml = simplexml_load_string($xdata);

echo "<br>namespaces that are used : ";
$namespace = $xml->getNamespaces();
foreach($namespace as $key => $value){

	echo "$key - $value <br>";
}

//use this if xmlns="http://google.com/API/XSD/SearchQ.xsd" is used in SearchRecords tag
	//$xml->registerXPathNamespace("mynewns", "http://google.com/API/XSD/SearchQ.xsd");
	//$result = $xml->xpath('//mynewns:SearchRecords');

//uncomment this to see it doesn't work, error caused by
// xmlns="http://google.com/API/XSD/SearchQ.xsd"
// Remove it from SearchRecords tags to get it work.
	$result = $xml->xpath('//SearchRecords');

echo "SearchRecords array has a size of : " . sizeof($xml) . "<br><br>";
echo "dumping array...<br>";
var_dump($result);


?>
</body>

    I've never had to work with XML namespaces yet, so I've not bothered to learn them or how to use them with SimpleXML. 🙂

    If SimpleXML doesn't seem to do what you need, you might want to take a look at the [man]DOM[/man] functions and see if they do.

      Write a Reply...