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 WPF 大屏看板表格背景图片设置
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示