2015-07-19 37 views
0

因此,我想通過屬性來遍歷XML,然後從協調標記中打印標記。這是結構:使用XPath和PHP存儲XML文檔時,標記信息未按需要存儲在數組中

<emp salesid="1"> 
    <report>07-14-2015_DPLOH_SalesID_1.pdf</report> 
    <report>07-17-2015_DPLOH_SalesID_1.pdf</report> 
    <report>07-14-2015_DTE_SalesID_1.pdf</report> 
    <report>07-14-2015_IDT_SalesID_1.pdf</report> 
    <report>07-14-2015_Kratos_SalesID_1.pdf</report> 
    <report>07-14-2015_Spark_SalesID_1.pdf</report> 
</emp> 

這裏是我的代碼:

$xml = new SimpleXMLElement($xmlStr); 

foreach($xml->xpath("//emp/report") as $node) { 
    //For all found nodes retrieve its ID from parent <emp> and store in $arr 
    $id = $node->xpath("../@salesid"); 
    $id = (int)$id[0]; 
    if(!isset($arr[$id])) { 
     $arr[$id] = array(); 
    } 

    //Then we iterate through all nodes and store <report> in $arr 
    foreach($node as $report) { 
     $arr[$id][] = (string)$report; 
    } 
} 

echo "<pre>"; 
print_r($arr); 
echo "</pre>"; 

但是,這是我得到的輸出:

Array 
(
    [1] => Array 
     (
     ) 

    [10] => Array 
     (
     ) 

...它繼續重複通過標籤的所有屬性,但從不用任何信息填充陣列。

如果有人能幫助告訴我我錯過了什麼,我將非常感激。我覺得我對於看起來應該比較簡單的事情感到失落了。

謝謝!

+0

以通用的方式執行此操作很困難,但難以從特定的XML生成特定的數組結構。迭代'emp'元素,讀取特定值並生成目標數組結構。 – ThW

+0

我重寫了代碼,但我有一些問題需要將標記信息存儲爲我需要的信息。如果您有任何見解,我將不勝感激! – Drew

回答

1

你非常接近。該代碼不起作用,因爲第二個for循環。外層循環將遍歷所有的report元素。所以,node是一個report元素。當你嘗試遍歷report的孩子時,那裏什麼也沒有。

相反的第二(內)循環,只要做到這一點:

$arr[$id][] = (string)$node; 

當我做到了,我得到了以下結果:

<pre> 
Array 
(
    [1] => Array 
     (
      [0] => 07-14-2015_DPLOH_SalesID_1.pdf 
      [1] => 07-17-2015_DPLOH_SalesID_1.pdf 
      [2] => 07-14-2015_DTE_SalesID_1.pdf 
      [3] => 07-14-2015_IDT_SalesID_1.pdf 
      [4] => 07-14-2015_Kratos_SalesID_1.pdf 
      [5] => 07-14-2015_Spark_SalesID_1.pdf 
     ) 
    ) 
0

我更新你的腳本稍有不同的工作:

$emp = new SimpleXMLElement($xmlStr); 

$id = intval($emp['salesid']); 
$arr = array(
    $id   => array(), 
); 

$lst = $emp->xpath('/emp/report'); 

while (list(, $text) = each($lst)) 
{ 
    $arr[$id][] = (string) $text; 
} 

echo "<pre>"; 
print_r($arr); 
echo "</pre>"; 

乾杯