Link to home
Start Free TrialLog in
Avatar of Matthew_Way
Matthew_Way

asked on

PHP SimpleXML count specific nodes

How do I count the number of "field" nodes in a XML document with SimpleXML ?

PHP Version 5.1.2, WindowsXP SP 2, Apache 2

I've tried with PHP count and Xpath count but I can't get either to work.

Here is my test code.

*** Sample PHP Code ***
<?php
$string = <<<XML
<?xml version="1.0" encoding="iso-8859-1"?>
<importschema name="import_filter.xml" delimiter="~">
      <field name="UNIQUE_IDENTIFIER" type="bigint" length="10" import ="true" />
      <field name="AGE" type="tinyint" length="2" import ="true" />
      <field name="TITLE" type="varchar" length="20" import ="true" />
      <field name="SURNAME" type="varchar" length="25" import ="true" />
      <field name="GIVEN" type="varchar" length="30" import ="true" />
      <field name="OCCUPATION" type="varchar" length="35" import ="true" />
</importschema>
XML;

$xml = simplexml_load_string($string);
$field_count = count($xml->field);

$xp = $xml->xpath('count( //field )');

print "Field Count $field_count,  XPath $xp";
Avatar of hernst42
hernst42
Flag of Germany image

Does
$xp = count($xml->xpath('//field'));
works for you or does
$i = 0;
foreach ($xml->field as $f) { ++$i; }
echo $i ."\n";
work. The xpath count does not work with simple xml. On my linux with the same php your example works (except the xpath-count)
Avatar of Matthew_Way
Matthew_Way

ASKER

Both of your sugestions work okay on my Windows machine.

Any idea why this statement always results in 1 ?

$field_count = count($xml->field);
ASKER CERTIFIED SOLUTION
Avatar of hernst42
hernst42
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial