1

Why can't I filter results on the attribute value rather than the index?

Something like this fails.

foreach ($portfolio->clientGroup[$id]->client['name=foo']->src as $src) {
   echo $src . '<br />';
}

But this works.

foreach ($portfolio->clientGroup[$id]->client[0]->src as $src) {
   echo $src . '<br />';
}
mmcglynn
  • 7,668
  • 16
  • 52
  • 76
  • X-Ref: [SimpleXML: Selecting Elements Which Have A Certain Attribute Value (Jun 2009)](http://stackoverflow.com/q/992450/367456) – hakre Jul 09 '13 at 09:43

2 Answers2

2

This does not work because SimpleXML is a lightweight implementation. Plus, you can't assume anything to work unless you have a specification.

You are looking for the xpath function of SimpleXMLElement objects, i.e.:

foreach ($portfolio->clientGroup[$id]->xpath("client[@name='foo']/src") as $src) {
   echo $src . '<br />';
}
phihag
  • 278,196
  • 72
  • 453
  • 469
  • Counter question: Are you sure that "name" isn't a child of , instead of an attribute? – Tomalak Feb 15 '09 at 17:54
  • Yes ("Why can't I filter results on the *attribute value* rather than the index?") – phihag Feb 15 '09 at 18:33
  • Oops. Seems my browser font is too small. ;-) Whatever, I added an XPath expression for both cases to my answer. FWIW, +1 from me. Your answer was a few seconds faster than mine anyway. – Tomalak Feb 15 '09 at 19:25
1

SimpleXML provides access to your document in form of a nested array. There is no way to place an XPath expression as the array index.

Try something like:

$query = "client[@name='foo']/src"; // if name is an attribute
$query = "client[name='foo']/src";  // if name is a child element

foreach ($portfolio->clientGroup[$id]->xpath($query) as $src ) {
   echo $src . '<br />';
}
Tomalak
  • 332,285
  • 67
  • 532
  • 628
  • Are you sure that "name" selects an attribute? Afaik, you need to prefix the name with an "@" sign. – phihag Feb 15 '09 at 17:37
  • The darn editor uses the "@" sign as some kind of shortcut for "Blockquote" or such. Everytime I press "@", it starts a new line, and I am forced to create the "@" somewhere else and copy/paste it in. Frustrating. Managed to get it wrong here. – Tomalak Feb 15 '09 at 17:41