0

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

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

was looking for this answer as my problem is similar to the topic. A shame he never accepted your answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.