因此,我想通過屬性來遍歷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
(
)
...它繼續重複通過標籤的所有屬性,但從不用任何信息填充陣列。
如果有人能幫助告訴我我錯過了什麼,我將非常感激。我覺得我對於看起來應該比較簡單的事情感到失落了。
謝謝!
以通用的方式執行此操作很困難,但難以從特定的XML生成特定的數組結構。迭代'emp'元素,讀取特定值並生成目標數組結構。 – ThW
我重寫了代碼,但我有一些問題需要將標記信息存儲爲我需要的信息。如果您有任何見解,我將不勝感激! –
Drew