dpvmjk0479 2015-07-19 05:56
浏览 51
已采纳

使用XPath和PHP存储XML文档时,标记信息不会像需要那样存储在数组中

So, I want to iterate through the XML by the attributes of and then print the tags from within the coordinating tag. This is the structure:

<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>

Here is the my code:

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

However, this is what I get for output:

Array
(
    [1] => Array
        (
        )

    [10] => Array
        (
        )

... and it continues to iterate through all of the attributes of tags, but never fills the array with any information.

If anyone could help tell me what I'm missing, I would GREATLY appreciate it. I feel like I'm losing my mind over what seems like should be rather simple.

Thanks!

  • 写回答

2条回答 默认 最新

  • dsrjs86444 2015-07-20 23:54
    关注

    You're very close. The code isn't working because of the second for loop. The outer loop will iterate through all of the report elements. So, node is a report element. When you try to iterate through the children of report, there's nothing there.

    Instead of the second (inner) loop, simply do this:

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

    When I did, I got the following result:

    <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
            )
        )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大