如何在属性名称上获取以下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>";
}
}
答案 0 :(得分: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>
。
答案 1 :(得分:0)
你走了。
foreach($xml->children() as $resources)
{
foreach($resources->children() as $resource => $data)
{
echo $data->field['name'];
echo "<br>";
echo $resource->attributes()->name;
}
}
答案 2 :(得分: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;
}
答案 3 :(得分:0)
你不是那么遥远。按名称查询元素而不是使用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
}
}
Outout:
---------------
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