bear
bear

Reputation: 11625

Getting XML node attributes

I'm using a custom XML parser here after getting a file via cURL.

here's the parsing function

function pd_xml_parser($rawxml) {
$xml_parser = xml_parser_create();
xml_parse_into_struct($xml_parser, $rawxml, $vals, $index);
xml_parser_free($xml_parser);
$params = array();
$level = array();
$alreadyused = array();
$x=0;
foreach ($vals as $xml_elem) {
    if ($xml_elem['type'] == 'open') {
        if (in_array($xml_elem['tag'],$alreadyused)) {
            $x++;
            $xml_elem['tag'] = $xml_elem['tag'].$x;
        }
        $level[$xml_elem['level']] = $xml_elem['tag'];
        $alreadyused[] = $xml_elem['tag'];
    }
    if ($xml_elem['type'] == 'complete') {
        $start_level = 1;
        $php_stmt = '$params';
        while($start_level < $xml_elem['level']) {
            $php_stmt .= '[$level['.$start_level.']]';
            $start_level++;
        }
        $php_stmt .= '[$xml_elem[\'tag\']] = $xml_elem[\'value\'];';
        @eval($php_stmt);
    }
}
return($params);
}

A sample document would look like:

 <api>
  <tickets>
   <ticket id="number">
    <data></data>
   </ticket>
  </tickets>
</api>

I'm currently calling each node, data using foreach. How would I extract the attribute from the ticket node, i.e the id attribute?

Thanks

Upvotes: 0

Views: 179

Answers (1)

Baba
Baba

Reputation: 95161

You can try

$xml = '<api>
  <tickets>
   <ticket id="111">
    <data></data>
   </ticket>
    <ticket id="222">
    <data></data>
   </ticket>

  </tickets>
</api>';

echo "<pre>";
$xml = new SimpleXMLElement($xml);
foreach ( $xml->tickets->children() as $ticket ) {
    $attribute = $ticket->attributes();
        print($attribute['id'].PHP_EOL);
}

Output

111
222

Upvotes: 2

Related Questions