I'm faily new XML within PHP, and was hoping you clever people out there would be able to help me. Let's say I have an xml document which is full of users. Let me give you an example one of the users:
<user name="Cajs">
<email>mail@cajs.co.uk</email>
<server>Alpha</server>
<referral>VQxwf3Wq4PS5WOqhljTDPUbA</referral>
<limit>10</limit>
<ips />
<network id="EsperNet" created="1388534400"/>
<network id="DALnet" created="1388534400"/>
<network id="Freenode" created="1388534400"/>
<network id="OnlineGamesNet" created="1388534400"/>
<network id="PonyChat" created="1388534400"/>
<network id="QuakeNet" created="1388534400"/>
<network id="Rizon" created="1388534400"/>
<network id="YourBNC" created="1388534400"/>
<network id="AthemeNet" created="1406458342"/>
</user>
How would I count the total amount of networks of "ALL" users who have the server Alpha.
Thanks for all help!
* UPDATE * Please is it possible for when the removed= part is added to the tag it's ignored, example below:
You can solve this with help of XPath:
$xml = simplexml_load_string($xml);
$results = array();
foreach($xml->xpath('//user[server[.="Alpha"]]') as $user) {
$results[] = array(
'name' => (string)$user->attributes()->name,
'network_count' => $user->network->count()
);
}
var_dump($results);
$xml = simplexml_load_string($xmlString);
$countUsers = 0;
for( $i = 0; $i < $xml->count(); $i++ ) {
if( $xml->user[$i]->server == 'Alpha' )
$countUsers++;
}
var_dump($countUsers);
With DomDocument it would just be:
$xpath->query('//user[server[text()="Alpha"]]/network')->length;
I'm sure it's the same in simplexml but I never use that lib.
For the second part it's:
$xpath->query('//user[not(@removed) and server[text()="Alpha"]]/network')->length;