1

I want to parse this xml file and use XPATH retrieve some fields (this is how I see xml file by the way, you can download it from here):

I try the following code to get the edition of the book:

$file_copac = "http://copac.ac.uk/search?isn=$isbn&rn=1&format=XML+-+MODS";
$xml = simplexml_load_file($file_copac) or die("cannot_get_data");
$temp = $xml->xpath('//edition');
var_dump($temp);

I also tried 'edition' but the result is empty array for both:

array(0) { }

I tried full path using '/mods/originInfo[1]/edition' which ended with an XPATH error. I solve problem with this notation:

$edition = (string)$xml->mods->originInfo[1]->edition;

However I wonder the problem with xpath.

Mehmed
  • 2,880
  • 4
  • 41
  • 62

1 Answers1

3

Looks like problem with default (empty) namespace, workaround for this:

$namespaces = $xml->getDocNamespaces(); 
$xml->registerXPathNamespace('__DEFAULT_NS__', $namespaces['']);
$r = $xml->xpath('//__DEFAULT_NS__:edition');

var_dump((string)$r[0]); //string(8) "8th. ed."
dev-null-dweller
  • 29,274
  • 3
  • 65
  • 85
  • Thanks for your effort. Could you explain it further? I somewhat sense this but I get confused since 'modsCollection' and 'mods' tags have namespace definitons. – Mehmed Nov 26 '12 at 10:44
  • 1
    Yes, they have namespace definition, but with no prefix. XPath does not use default namespace, so it returns only non namespaced elements. To query elements from default namespace you have to provide prefix for it, and since here prefix is empty, you have to create an alias for it, then use this alias in your query. – dev-null-dweller Nov 26 '12 at 17:19
  • Is this a PHP-specific or SimpleXML problem? I can get values without any namespace definitions in a C# program. Thank you again for the clear explanation. – Mehmed Nov 26 '12 at 18:10
  • It's not only `SimpleXML`, in php `DOMDocument` behaves exactly the same way so and from quick search it appears that in C# also - http://stackoverflow.com/questions/585812/using-xpath-with-default-namespace-in-c-sharp so it may depend on implementation – dev-null-dweller Nov 26 '12 at 19:58