mmcglynn
mmcglynn

Reputation: 7672

Attribute Value Selection in SimpleXML

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 />';
}

Upvotes: 1

Views: 3107

Answers (2)

Tomalak
Tomalak

Reputation: 338416

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 />';
}

Upvotes: 1

phihag
phihag

Reputation: 288298

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 />';
}

Upvotes: 2

Related Questions