在通过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调用数据。如何从ticket节点提取属性,即id属性?
谢谢
发布于 2012-10-10 09:07:04
你可以试试
$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
https://stackoverflow.com/questions/7997034
复制相似问题