1

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.

3 Answers 3

3

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 '.';   
}
Sign up to request clarification or add additional context in comments.

2 Comments

Cheers. I have tried running that but still get no matches / results. Very frustrating!
$doc->loadXML($data); was the issue what a tool! Cheers guys!
0

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.

1 Comment

Cheers. I have tried running that but still get no matches / results. Very frustrating!
0

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) {
  //...
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.