我在通过cURL获取文件后在这里使用自定义XML解析器。
这是解析功能
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);
}
示例文档如下所示:
<api>
<tickets>
<ticket id="number">
<data></data>
</ticket>
</tickets>
</api>
我正在使用foreach调用每个节点,数据。如何从故障单节点中提取属性,即id属性?
由于
答案 0 :(得分:2)
你可以尝试
$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);
}
输出
111
222