我有一个这样制作的XML:
<marketstat>
<type id="17889">
<buy>
<volume>15005046</volume>
<avg>704.84</avg>
<max>755.88</max>
<min>428.10</min>
<stddev>58.87</stddev>
<median>753.77</median>
<percentile>755.87</percentile>
</buy>
<sell>
<volume>43601243</volume>
<avg>1017.32</avg>
<max>1697.90</max>
<min>917.94</min>
<stddev>190.56</stddev>
<median>953.01</median>
<percentile>917.94</percentile>
</sell>
</type>
<type id="44">
<buy>
<volume>15005046</volume>
<avg>704.84</avg>
<max>755.88</max>
<min>428.10</min>
<stddev>58.87</stddev>
<median>753.77</median>
<percentile>755.87</percentile>
</buy>
<sell>
<volume>43601243</volume>
<avg>1017.32</avg>
<max>1697.90</max>
<min>17.9</min>
<stddev>190.56</stddev>
<median>953.01</median>
<percentile>917.94</percentile>
</sell>
</type>
</marketstat>
是否有一种方法,我可以采取属性id内的标签类型和转换它在一个php变量具有相同的名字给它在xml中的值?
我的目标是为每个id有一个变量,并在xml中分配sell->min的值,以便之后我可以调用它来进行一些计算。
类似:
$17889 = "917.94";
$44 = "17.9";
或者我唯一能做的就是使用$xml->xpath('//marketstat/type[@id="17889"]/sell/min');每次我都想得到它的值?
是,不是。这是可能的,但不可能有像'$17889'这样的变量,因为变量名必须以字母或下划线开头。http://php.net/manual/en/language.variables.basics.php
现在,如果您想要$_17889 = "917.94";
和$_44 = "17.9";
这样的内容,那么在id前面加上下划线,您可以这样做:
$result = $xml->xpath('//marketstat/type');
while(list( , $node) = each($result)) {
$attr = $node->attributes();
$id = "_" . $attr['id'];
$$id = $node->sell[0]->min[0];
}
多亏你的建议,我终于解开了这个谜。
我刚刚"黑"了你的代码在一些我觉得更舒服的使用,一个正常的foreach循环
foreach ($xml->marketstat->type as $type)
{
$typeid = $type[id];
$id = "_" . $typeid;
$$id = $type->sell->min;
}