user343035
user343035

Reputation: 145

PHP XPath issue

Having a real bugger of an Xpath issue. I am trying to match the nodes with a certain value.

Here is an example XML fragment.

http://pastie.org/private/xrjb2ncya8rdm8rckrjqg

I am trying to match a given MatchNumber node value to see if there are two or more. Assuming that this is stored in a variable called $data I am using the below expression. Its been a while since ive done much XPath as most thing seem to be JSON these days so please excuse any rookie oversights.

$doc = new DOMDocument;
$doc->load($data);
$xpath = new DOMXPath($doc);
$result = $xpath->query("/CupRoundSpot/MatchNumber[.='1']");

I need to basically match any node that has a Match Number value of 1 and then determine if the result length is greater than 1 ( i.e. 2 or more have been found ).

Many thanks in advance for any help.

Upvotes: 1

Views: 62

Answers (3)

ThW
ThW

Reputation: 19492

You have to register the namespace. After that you can use the Xpath count() function. An expression like that will only work with evaluate(), not with query(). query() can only return node lists, not scalar values.

$dom = new DOMDocument();
$dom->loadXml($xml);
$xpath = new DOMXpath($dom);
$xpath->registerNamespace('fl', 'http://www.fixtureslive.com/');

var_dump(
  $xpath->evaluate(
    'count(/fl:ArrayOfCupRoundSpot/fl:CupRoundSpot[number(fl:MatchNumber) = 1])'
  )
);

Output:

float(2)

DEMO: https://eval.in/130366

To iterate the CupRoundSpot nodes, just use foreach:

$nodes = $xpath->evaluate(
  '/fl:ArrayOfCupRoundSpot/fl:CupRoundSpot[number(fl:MatchNumber) = 1]'
);
foreach ($nodes as $node) {
  //...
}

Upvotes: 0

VolkerK
VolkerK

Reputation: 96159

Your XML document has a default namespace: xmlns="http://www.fixtureslive.com/".
You have to register this namespace on the xpath element and use the (registered) prefix in your query.

$xpath->registerNamespace ('fl' , 'http://www.fixtureslive.com/');
$result = $xpath->query("/fl:ArrayOfCupRoundSpot/fl:CupRoundSpot/fl:MatchNumber[.='1']");
foreach( $result as $e ) {
    echo '.';   
}

Upvotes: 3

Mark Veenstra
Mark Veenstra

Reputation: 4739

The following XPath:

/CupRoundSpot[MatchNumber = 1]

Returns all the CupRoundSpot nodes where MatchNumber equals 1. You could use these nodes futher in your PHP to do stuff with it.

Executing:

count(/CupRoundSpot[MatchNumber = 1])

Returns you the total CupRoundSpot nodes found where MatchNumber equals 1.

Upvotes: 0

Related Questions