1

如何在属性名称上获取以下 xml 的值。

    <list version="1.0">
<meta>
<type>resource-list</type>
</meta>
<resources start="0" count="165">
<resource classname="Quote">
<field name="name">USD/KRW</field>
<field name="price">1131.319946</field>
<field name="symbol">KRW=X</field>
<field name="ts">1371547710</field>
<field name="type">currency</field>
<field name="volume">0</field>
</resource>
<resource classname="Quote">
<field name="name">SILVER 1 OZ 999 NY</field>
<field name="price">0.045962</field>
<field name="symbol">XAG=X</field>
<field name="ts">1371505422</field>
<field name="type">currency</field>
<field name="volume">7</field>
</resource>....

有165个这样的结构

想要获取 SILVER 1 OZ 999 NY 0.045962 XAG=X 1371505422 等

到目前为止,我的代码就像

$xml = simplexml_load_string($data);

foreach($xml->children() as $resources)
{
    foreach($resources->children() as $resource => $data)
    {
        echo $data->field['name'];
        echo "<br>";
    }


}
4

4 回答 4

1

根据评论中的 XML,它应该是:

$xml = simplexml_load_string($data);

foreach($xml->resources->resource as $resource)
{
    foreach($resource->field as $field)
    {
        echo $field->attributes()->name; // e.g. name, price, symbol
        echo (string)$field; // this is the content, e.g. SILVER 1 OZ 999 NY
    }
}

请注意,$xml始终包含根元素,在这种情况下为<list>.

演示

于 2013-06-18T10:51:12.343 回答
0

更正的代码:

<quote>
<name>test</name><price>567</price><symbol>xyz</symbol><ts>1371505422</ts>
<type>currency</type>
<volume>7</volume>
</quote>
$xmlObject = new SimpleXMLElement($xmlstring);
foreach ($xmlObject->children() as $node){
echo $node->Company;
echo $node->price;
echo $node->symbol;
echo $node->ts;
echo $node->type;
echo $node->volume;
}
于 2013-06-18T11:16:42.270 回答
0

你并没有那么远。通过元素名称而不是 using 查询元素children(),您只需要children()不在元素命名空间内的子元素的方法。在您的代码中,您刚刚查询了错误的数据,请参见以下示例(Demo):

$xml = simplexml_load_string($data);

foreach($xml->resources->resource as $resource)
{
    echo "---------------\n";
    foreach($resource->field as $field)
    {
        echo $field['name'], ': ',  // e.g. name, price, symbol
             $field, "\n";          // this is the content, e.g. SILVER 1 OZ 999 NY
    }
}

输出:

---------------
name: USD/KRW
price: 1131.319946
symbol: KRW=X
ts: 1371547710
type: currency
volume: 0
---------------
name: SILVER 1 OZ 999 NY
price: 0.045962
symbol: XAG=X
ts: 1371505422
type: currency
volume: 7

这在基本的 simplexml 使用示例中进行了概述和解释,请参阅: http: //php.net/simplexml.examples-basic

于 2013-06-18T14:37:11.450 回答
0

干得好。

foreach($xml->children() as $resources)
{
foreach($resources->children() as $resource => $data)
{
    echo $data->field['name'];

    echo "<br>";
    echo $resource->attributes()->name;

}


}
于 2013-06-18T10:56:59.793 回答