使用XPath和PHP存储XML文档,标签信息不按需要存储在数组中


Storing XML Document with XPath and PHP, tag info isn't storing in array like needed

所以,我想通过的属性遍历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
        (
        )

…它继续遍历标记的所有属性,但从不用任何信息填充数组。

如果有人能告诉我我错过了什么,我将非常感激。我觉得我在为看似简单的事情失去理智。

谢谢!

你很接近了。由于第二个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
        )
    )

我更新了你的脚本工作略有不同:

$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>";

欢呼