I have an array list of tags from xml file and im using xml file to add some posts to wordpress. So i need to convert xml array to comma separated list for tags to import in my posts.
This is an xml file example
<tags>
<tag>tag1</tag>
<tag>tag2</tag>
<tag>tag3</tag>
</tags>
So when i call this file in my .php file and use print_r to get the output i get this
SimpleXMLElement Object (
[tag] => Array (
[0] => SimpleXMLElement Object ( )
[1] => SimpleXMLElement Object ( )
[2] => SimpleXMLElement Object ( )
[3] => SimpleXMLElement Object ( )
)
)
So 0 1 2 3 are tags and values are stored in SimpleXMLElement Object ( ) i read it’s normal to not get values when using print_r but i know the values are there.
Now i need to convert this as a list at the end to get this result
$post_tags = tag1, tag2, tag3;
so that i can use $post_tags in my function.
Assuming your object (the one on which you called
print_r()
is$xml
), you would loop over$xml->tag
and append each child object’s contents to an array. Finally, implode the array to a string.You indicate that you need a list for
$post_tags
, but your syntax above is ambiguous as to whether you wanted a string or an array. If you wanted an array, you have it in$post_tags_arr
prior to theimplode()
.If you feel like being clever, and the
<tag>
nodes reside at the same level and have no children, you can simply cast them as a regular array, which will result in their string values.