Re: XPath avg(), min(), max() functions not found

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Hi Alex,

Alex wrote:
Hi all. I'm trying to use XPath avg(), min() and max() functions
without success. Others functions like count() or sum() works correctly.

Here is the code I'm using (PHP 5.1):

<?php

$xml_str = '
<stats>
  <cards>
    <card name="My card">
      <type name="visits">25</type>
      <type name="clicks">7</type>
    </card>
    <card name="My other card">
      <type name="visits">50</type>
      <type name="clicks">3</type>
    </card>
  </cards>
</stats>
';

$xml_doc = new DOMDocument();
$xml_doc->loadXML($xml_str);

$xpath = new DOMXPath($xml_doc);

$cards_avg = $xpath->evaluate("avg(//card/type[@name='visits'])");
var_dump($cards_avg);

$cards_sum = $xpath->evaluate("sum(//card/type[@name='visits'])");
var_dump($cards_sum);

?>

min(), max() and avg() don't exist in XPath 1.0 which is the version implemented in libxml2. You need to calculate these yourself. For example:

/* Find the average */
$cards_avg = $xpath->evaluate("sum(//card/type[@name='visits']) div count(//card/type[@name='visits'])");
var_dump($cards_avg);

$cards_sum = $xpath->evaluate("sum(//card/type[@name='visits'])");
var_dump($cards_sum);

/* Find lowest visits */
$cards_min_nodes = $xpath->query("//card/type[@name='visits']/text()");
$min = NULL;
foreach ($cards_min_nodes AS $node) {
	$val = (int)$node->nodeValue;
	if (is_null($min) || $min > $val) {
		$min = $val;
	}
}
print 'Minimum Visits: '.$min."\n";

/* Find maximum visits */
$cards_max_nodes = $xpath->query("//card/type[@name='visits']/text()");
$max = NULL;
foreach ($cards_max_nodes AS $node) {
	$val = (int)$node->nodeValue;
	if (is_null($min) || $max < $val) {
		$max = $val;
	}
}
print 'Maximum Visits: '.$max."\n";

Rob

--
rrichards@xxxxxxxxxxxxxxxx
author of Pro PHP XML and Web Services from Apress

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux