I need to select nodes from xml, conditions see below. I am using simplexml, so the xpath has to be 1.0.
XML snippet:
<scales>
<scale id="1" gender="*" age="*">
<d scid="hi" raw="10" t="76" />
<d scid="pn" raw="12" t="80" />
</scale>
<scale id="2" gender="m" age="*">
<d scid="hi" raw="8" t="79" />
<d scid="pn" raw="2" t="50" />
</scale>
<scale id="3" gender="*" age="19-39">
<d scid="hi" raw="0" t="48" />
<d scid="pn" raw="10" t="49" />
</scale>
</scales>
Now, I want to select the t
-Attribute of a <d>
node that has...
raw="10" AND scid="hi"
$result=$xml->xpath('//d[@scid="hi"][@raw="10"]/@t');
And its parent-node <scale>
has...
(gender="*" OR gender="m") AND (age="*" OR age="39-59")
$result=$xml->xpath('//scale[@gender="*" or @gender="m"][@age="*" or @age="39-59"]');
I'd like to get this with 1 xpath-statement from my simplexml-object $xml
.
Just combine your two XPath query...
$str=<<<XML
<scales>
<scale id="1" gender="*" age="*">
<d scid="hi" raw="10" t="76" />
<d scid="pn" raw="12" t="80" />
</scale>
<scale id="2" gender="m" age="*">
<d scid="hi" raw="8" t="79" />
<d scid="pn" raw="2" t="50" />
</scale>
<scale id="3" gender="*" age="19-39">
<d scid="hi" raw="0" t="48" />
<d scid="pn" raw="10" t="49" />
</scale>
</scales>
XML;
$xml=simplexml_load_string($str);
foreach($xml->xpath('//scale[@gender="*" or @gender="m"][@age="*" or @age="39-59"]/d[@scid="hi"][@raw="10"]/@t') as $t)
{
echo $t;
}
Outputs 76
.
ok quick read into xpath seems like you can do attribute matches something like this
$path = "(scale[@gender=\"*\"]|scale[@gender=\"m\"]) & (scale[@age=\"*\"]|scale[@age=\"39-59\"])";
$scale= $xml->xpath($path);
This should return you the actual scale tag you want. Then you can foreach loop through the tags within the returned $scale and pull the standard attributes using something like this (note not accurate but right concept)
foreach($scale->d[0]->attributes() as $a => $b => $c) {
echo "t=$c\"
";
}