2012-04-03 79 views
0

屬性我有以下搶XML使用XPath和PHP

$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

「我只返回一條記錄」 - 這是什麼意思?我沒有看到任何代碼返回任何東西。 – LarsH 2012-04-03 14:23:15

回答

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 
     ) 

) 

希望它能幫助。 。

+0

這也不起作用。 XML是格式化爲這樣 <會員ID = 「」> 數據 <會員ID = 「」> 日期 我還是不管什麼只返回1號獲得的點擊次數每個分支機構的工作,但沒有運氣的ID – 2012-04-03 14:38:32

+0

這個問題對我來說似乎只有1個子公司節點,我不能強迫它循環其他子節點 – 2012-04-03 14:44:50

+0

@ bret-thomas - 檢查我編輯的答案。 – 2012-04-04 05:49:40