I have a PHP xpath query that works well for searching on a single node of my XML file. In simplified form, it looks like this:
xxxxxxxxxx
$url = 'myfile.xml';
$xml = simplexml_load_file($url);
$xml->registerXPathNamespace("h", "https://library.example.ac.uk");
$found = $xml->xpath("//h:row[h:AUTHOR1[contains(.,'$search')]]");
...
The limitation is that it only finds AUTHOR1, but this XML library catalog file can contain multiple authors, like this sample entry:
My current search will only find “FABER”, but I would like it also to be able to find “MAZLISH”.
I thought this would be a job for starts-with
, but no syntax I have tried will work. I thought I could do something like:
xxxxxxxxxx
$xml->xpath("//h:row[h:[starts-with(name(), 'AUTHOR')[contains(...
But I cannot get any variant of that to work. (The problem is not the nesting of quotes or brackets, I’m quite sure.) And I have tried both name
and local-name
for the starts-with
bit.
So! How to find hits on any of the AUTHOR1
, AUTHOR2
, AUTHORn
… nodes?
The problem is more with how you select the nodes, name()
will give you the name including the prefix, so you don’t need to specify this as a separate part of the query (I think as it’s the default prefix it is blank). So the value will be AUTHOR1
etc. So change the way that you select the author nodes to just use /*[starts-with(name(), 'AUTHOR')]
…
xxxxxxxxxx
$found = $xml->xpath("//h:row[*[starts-with(name(), 'AUTHOR')][contains(.,'$search')]]");
You can always add /..
to the end of the XPath to backtrack to the row element:
//h:row/*[starts-with(name(), 'AUTHOR')][contains(.,'$search')]/..