您好,是否有人可以帮助我。
下面的第一个代码基本上计算了每个XML记录,并以所需的格式输出
旧代码
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://xxxxx');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$xml_string = curl_exec ($ch);
curl_close ($ch);
// parse data
$xml=simplexml_load_string($xml_string);
// fix to n slots, zero padded
$slots=6;
$counter = substr((string)(pow(10,$slots)+count($xml)),1,$slots);
for($c=0; $c<strlen($counter); $c++)
{
echo("<span>".$counter[$c]."</span>");
}
Out put
<span>1</span><span>3</span><span>5</span><span>6</span><span>8</span><span>8</span>
这一切都还可以,但现在XML Feed已经改变,只是输出以下内容。
<Data>
<Row>
<Column name="cam" type="xs:int">000</Column>
<Column name="camN" type="xs:string">hello</Column>
<Column name="numer" type="xs:int">1</Column>
</Row>
<Row>
<Column name="cam" type="xs:int">000</Column>
<Column name="camN" type="xs:string">hello</Column>
<Column name="numer" type="xs:int">985</Column>
</Row>
<Row>
<Column name="cam" type="xs:int">000</Column>
<Column name="camN" type="xs:string">hello</Column>
<Column name="numer" type="xs:int">1</Column>
</Row>
</Data>
我需要输出相同的输出,但不确定我如何从每个记录中取出数值+它们然后输出它们确保我有6个结构,即使它最终以000005作为值
干杯
更新
抱歉,我需要将numer值加在一起得到一个totel所以如果totel是987我需要它输出:
<span>0</span><span>0</span><span>0</span><span>9</span><span>8</span><span>7</span>
答案 0 :(得分:2)
SimpleXml是最简单的方法。鉴于您提供的XML:
$xml = '
<Data>
<Row>
<Column name="cam" type="xs:int">000</Column>
<Column name="camN" type="xs:string">hello</Column>
<Column name="numer" type="xs:int">5220</Column>
</Row>
<Row>
<Column name="cam" type="xs:int">000</Column>
<Column name="camN" type="xs:string">hello</Column>
<Column name="numer" type="xs:int">4220</Column>
</Row>
<Row>
<Column name="cam" type="xs:int">000</Column>
<Column name="camN" type="xs:string">hello</Column>
<Column name="numer" type="xs:int">3220</Column>
</Row>
</Data>
';
$xml = simplexml_load_string($xml);
$numer_sum = 0;
// sums the value of columns
foreach ($xml->Row as $row) {
$numer_sum += (int)$row->Column[2];
}
或者,您可以使用xpath确保始终使用name =“numer”对Column元素求和,即使xml列的顺序发生更改:
$xml = simplexml_load_string($xml);
// get only the column elements with name="numer"
$xpath_result = $xml->xpath('Row/Column[@name="numer"]');
$sum = 0;
foreach ($xpath_result as $numer) {
$sum += (int)$numer[0];
}
echo $sum;
答案 1 :(得分:1)
您可以使用xpath来获取所需的节点,如下所示:
$xml = simplexml_load_string( $xml);
$elements = $xml->xpath( "/Data/Row/Column[@name='numer']");
$sum = 0;
foreach( $elements as $el)
{
$sum += $el[0];
}
echo $sum; // Prints 12660
现在,要获得所需的输出,请用零填充数字,将其拆分为1个字符的块,然后输出,如下所示:
$formatted = sprintf('%06d', $sum);
echo '<span>' . implode( '</span><span>', str_split( $formatted)) . '</span>';