How to concatenate similar tags in a XML file

前端 未结 1 1432
一向
一向 2021-01-27 05:43

There can be one or many similar XML tags inside a single XML record set. If there are many, I need them to be in a one tag, comma separated. This is the XML I have now.

<
相关标签:
1条回答
  • 2021-01-27 06:24

    This can be done with xpath. Here is an example with Simplexml:

    You can first find all the first leafs:

    foreach ($xml->xpath('//*[not(*) and not(preceding-sibling::*)]') as $firstLeaf) {
        ...
    }
    

    and then you concat the text together with all the following leafs:

        $followingWithSameName = 'following-sibling::*[name(.) = name(preceding-sibling::*[last()])]';
        // change the text of the first leaf
        $firstLeaf[0] = implode(', ', $firstLeaf->xpath(".|$followingWithSameName"));
    

    and then you remove all the following leafs:

        // remove all following leafs with the same name
        foreach ($firstLeaf->xpath($followingWithSameName) as $leaf) {
            unset($leaf[0]);
        }
    

    Demo

    0 讨论(0)
提交回复
热议问题