PHP simplexml how to print attributes of child nodes

28 views Asked by At

How do I print the attributes of all data nodes that are under staff?

values.xml

<?xml version="1.0" encoding="utf-8"?>
<dataset>
  <data name="region1">

    <staff>
      <data type="clerical" name="name_1" shift="1" />
      <data type="clerical" name="name_2" shift="2" />
    </staff>

  </data>
</dataset>

php script

<?php

$xml = simplexml_load_file('values.xml');
$node = $xml->xpath('/dataset/data[@name="region1"]');

if ($node) {
  echo 'Node found. Node count = '.count($node);

  echo '<pre>';
    $sha = array();
    $sha = $node[0]->staff->data->attributes();
  echo '</pre>';

} else {
  echo 'Could not find specified node.';
}

echo '<pre>';
print_r($sha);
echo '</pre>';

foreach ($sha as $key => $value) {
  echo $key.': '.$value.'<br>';
}

?>

Desired output:

type: clerical
name: name_1
shift: 1
    
type: clerical
name: name_2
shift: 2

With the above, it'll print only a single nodes attributes. Which is a bit of a mystery.

0

There are 0 answers