Hello I need some help to find my XML elements with PHP and xpath.
This is a part of my xml:
"processen": {
"proces": [
{
"@attributes": {
"id": "B1221"
},
"velden": {
"kernomschrijving": "activiteit aanleggen alarminstallatie",
"model-kernomschrijving": "aanleggen alarminstallatie",
"naam": "Het beoordelen van een alarminstallatie",
"standaard-dossiernaam": {
"@attributes": {
"ref": "SCN0000029"
}
},
"[tag:taakveld]": "Bouwzaken & Procedures",
"proceseigenaar": "Bouwzaken",
"toelichting-proces": "bla die bla.",
"aanleiding": "Dit werkproces wordt intern getriggerd.",
"opmerking-proces": {
"@attributes": {
"ref": "SCN0000036"
}
},
"exportprofiel": {
"@attributes": {
"ref": "SCN0000037"
},
},...
For example I want to be able to find the id (fast) and access all the elements under the id B1221
I tried this in al kind of variants but none works:
$xml = simplexml_load_file( $filename );
$proces = $xml->xpath("//processen/proces/@attributes/id=B1221");
$proces = $xml->xpath("//processen/proces[@attributes/id=B1221]");
It always returns an empty array...
Thanks for your help.
CodePudding user response:
What you've shown there is not the XML; it is some kind of representation of a PHP object which has been produced by parsing the XML, and through which you can access the content of the XML.
That may sound like a pedantic distinction, but it's actually key to your problem: XPath expressions aren't specific to PHP, and so aren't searching through this structure; they are a standard language for searching through the XML itself.
So to construct the correct XPath expression, you need to look only at the actual XML. From the representation you show, I'm guessing it looks, in part, something like this:
<processen>
<proces id="B1816">
<velden>
<kernomschrijving>activiteit aanleggen alarminstallatie</kernomschrijving>
<model-kernomschrijving>aanleggen alarminstallatie</model-kernomschrijving>
<naam>Het beoordelen van een alarminstallatie</naam>
</velden>
</proces>
</processen>
In XPath, you access elements (tags) by name, attributes (like id="..."
) with a leading @
, and literal strings in double-quotes. The [...]
operator means something like "has", so [@foo="bar"]
means "has an attribute foo
whose value is the string bar
".
Which gives you this:
$xml = simplexml_load_file( $filename );
$proces = $xml->xpath('//processen/proces[@id="B1816"]');
echo $proces[0]->asXML();
(Here's a live demo of that example.)
It looks like you may also have namespaces in there (tags with :
in the name); those require some extra tricks discussed in this reference question.