在xml属性中获取简单数据

时间:2014-06-04 10:04:55

标签: php xml

我希望以这种简单的XML格式获取并回显数据:

<top>
<file>
<my data="first"/>
</file>
<file>
<my data="second"/>
</file>
</top>

我想用php回声:

first,second

我需要提供XML文件的路径并获得结果。

怎么做?

1 个答案:

答案 0 :(得分:2)

首先,你需要使用simplexml_load_string()函数提取值,然后你需要循环这些值。由于firstsecond是属性,因此您还需要使用attributes()。考虑这个例子:

$raw_xml = '<top>
<file>
<my data="first"/>
</file>
<file>
<my data="second"/>
</file>
</top>';
$data = array();
$xml = simplexml_load_string($raw_xml);
foreach($xml->file as $key => $value) {
    $value = reset($value);
    $data[] = (string) $value->attributes()['data'];
}

echo "<pre>";
print_r($data);
echo "</pre>";

示例输出:

Array
(
    [0] => first
    [1] => second
)

编辑:如果你想回声试试这个。

echo implode(',', $data); // should output first,second
相关问题