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