dpvmjk0479 2015-07-18 21: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 15: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条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部