我有以下
$records = $xml->xpath("//Affiliates/Affiliate");
foreach ($records as $record){
$Clicks = $record->StatRow->Statistics->Clicks;
$Id = $record->Affiliate['Id'];
}
所有这些都有效,但我无法弄清楚如何从联盟节点获取节点属性“id”。
$records = $xml->xpath("//Affiliates");
foreach ($records as $record){
$Clicks = $record->Affiliate->StatRow->Statistics->Clicks;
$Id = $record->Affiliate['Id'];
}
这也可以,但是循环中断了,我只返回一条记录,我错过了什么?
答案 0 :(得分:0)
试试这个:
假设你的xml是这样的:
<!-- SAVE THIS FILE AS affiliate.xml -->
<?xml version="1.0" encoding="UTF-8"?>
<Affiliates>
<Affiliate Id="1">
<StatRow>
<Statistics>
<Clicks>click1</Clicks>
</Statistics>
</StatRow>
</Affiliate>
<Affiliate Id="2">
<StatRow>
<Statistics>
<Clicks>click2</Clicks>
</Statistics>
</StatRow>
</Affiliate>
</Affiliates>
您的PHP代码:
<?php
// load the xml file
$file = simplexml_load_file( 'affiliate.xml' );
$records = $file->xpath("//Affiliates/Affiliate");
$data = array();
foreach ($records as $key => $record) {
$data[ $key ][ 'id' ] = ( int ) $record['Id'];
$data[ $key ][ 'clicks' ] = ( string ) $record->StatRow->Statistics->Clicks;
}
// check data
print_r($data);
?>
打印:
Array
(
[0] => Array
(
[id] => 1
[clicks] => click1
)
[1] => Array
(
[id] => 2
[clicks] => click2
)
)
希望有所帮助......