0

I have an XML file (below) that I am trying to parse with PHP.

<content>
  <row label='DEV'>
   <cell href="exUrl('URL')"  status='0'>12345</cell>
   <cell href="exUrl('URL')"  status='1'>12345</cell>
   <cell href="exUrl('URL')"  status='1'>12345</cell>
   <cell href="exUrl('URL')"  status='1'>12345</cell>
   <cell href="exUrl('URL')"  status='1'>12345</cell>
  </row>
  <row label='DEV2'>
   <cell href="exUrl('URL')"  status='1'>56789</cell>
   <cell href="exUrl('URL')"  status='1'>56789</cell>
   <cell href="exUrl('URL')"  status='1'>56789</cell>
   <cell href="exUrl('URL')"  status='1'>56789</cell>
   <cell href="exUrl('URL')"  status='0'>56789</cell>
  </row>
 </content>

I'm currently using PHP to sum a number of 'rows' from an XML document (example below).

$dom = new DOMDocument();
$html = $dom->loadHTMLFile("XML.xml");
$dom->preserveWhiteSpace = false;
$tables = $dom->getElementsByTagName('content');
$rows = $tables->item(0)->getElementsByTagName('row');
foreach ($rows as $row)
{
    $cols = $row->getElementsByTagName('cell');
    $totalValues += $cols->item(4)->nodeValue;
}

I've updated the for loop to include an if statement to check the status value, however this doesn't seem to be working.

foreach ($rows as $row)
{
    $cols = $row->getElementsByTagName('cell');
    $totalValues += $cols->item(4)->nodeValue;
    if(($cols->item(4)->getElementsByTagName('status')->nodeValue) == 0) {
        $flag = 0;
    }
}

Can anyone assist with what I'm doing wrong here?

1
  • $cols->item(4)->getAttribute('status') == 0 Commented Jul 20, 2016 at 7:09

1 Answer 1

1

status is an attribute node, not an element node. Here are several ways to get the value. The easiest is just to read it from the element node:

if ($cols->item(4)->getAttribute('status') == 0) { ...

Or you can fetch the attribute node and read its value.

if ($cols->item(4)->getAttributeNode('status')->value == 0) { ...

Last, you can optimize you loops using Xpath and use an Xpath expression to set $flag.

$document = new DOMDocument();
$document->load($xmlFile);
$xpath = new DOMXpath($document);

$total = 0;
foreach ($xpath->evaluate('/content/row/cell[5]') as $cell) {
  $total += $cell->nodeValue;
}

$flag = $xpath->evaluate('count(/content/row/cell[5][@status=0]) > 0');

var_dump($total, $flag);

The first Xpath expression /content/row/cell[5] fetches all cell element nodes, that have the fifth position inside /content/row.

In the second experession that list is filtered by the value of the status attribute. The cell nodes with the status 0 are counted. If that count is greater then 0 the expression return true.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.