1

I'm stuck parsing this label with SimpleXML PHP.

This is my file:

<cpe-item name="cpe:/a:%240.99_kindle_books_project:%240.99_kindle_books:6::">
    <cpe-23:cpe23-item name="cpe:2.3:a:\*:*:*:*:*:*:*:*:*:*"/>
</cpe-item>

And I want to parse name content on cpe-23:cpe23-item.

This is my code for now:

foreach ($xml->{'cpe-item'} as $cpe) {
  echo $cpe->children('cpe-23', TRUE) // This is the line I have to modify
}
Ganesh Sittampalam
  • 28,821
  • 4
  • 79
  • 98
ndnd
  • 11
  • 1

1 Answers1

0

$cpe->children('cpe-23', TRUE) returns all the children in the namespace with prefix cpe-23:.

To get to a particular child, the easiest way is to reference it by name, in this case, ->cpe23-item, since the element is <cpe23-item ...>. However, this will confuse PHP's parser, because - would normally mean "minus"; you can avoid this using {} around the name, like ->{'cpe23-item'}, with the name itself encapsulated in apostrophes.

To get to an attribute of that element, you would normally use array access, e.g. ['name']. However, a quirk of XML namespaces means that the name= attribute here is in no namespace, so you have to use the ->attributes() function to "leave" the cpe-23 namespace you "entered" with the ->children() call, giving you ->attributes(null)->name.

Putting it all together, you have:

echo $cpe->children('cpe-23', TRUE)->{'cpe23-item'}->attributes(null)->name;
Arbiter
  • 450
  • 5
  • 26
IMSoP
  • 89,526
  • 13
  • 117
  • 169