Q:

Get attribute of XML tag using xml_parse_into_struct in PHP

I have an XML file like this:
<site>
    <pages>
        <page number="1">main page</page>
        <page number="2">about</page>
        <page number="3">contacts</page>
    </pages>
</site>

I need to print 3 parameters with the format type : number : value.
My PHP code is as follows:
$xml = file_get_contents('file.xml');
$p = xml_parser_create();
xml_parse_into_struct($p, $xml, $vals, $index);
xml_parser_free($p);

foreach ($vals as $val) {
    print(" {$val["type"]} : {$val["number"]} : {$val["value"]}<br><br>\n");
}

This prints the type and the value, but not the number. How can I print the "number" attribute of an XML tag?

A:

To debug this, you could just add in print_r( $val ); into the foreach loop. What you'll see there is that there is an attributes array in the $val, which contains the number. So, change the foreach loop to be something like:
foreach ($vals as $val) {
    if ( 'PAGE' !== $val['tag'] ) {
        continue;
    }
  print(" {$val['type']} : {$val['attributes']['NUMBER']} : {$val['value']}<br><br>\n");
}

And then you should have it. Although, I'm not sure if you want $val['type'], but you might want $val['tag']. $val['type'] will be either open, closed, or complete, which refers to the tag as its being parsed. $val['tag'] will be SITE, PAGES, or PAGE, with the bit of xml that you referenced in the post.

