XML array to comma separated list

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

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

Related posts

Leave a Reply

1 comment

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

    // An array to hold it temporarily
    $post_tags_arr = array();
    
    foreach ($xml->tag as $t) {
      // Cast it to a string to get the text value back
      $post_tags_arr[] = (string)$t;
    }
    // Implode the array to a string
    $post_tags = implode(', ', $post_tags_arr);
    echo $post_tags;
    

    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 the implode().

    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.

    // Cast it to an array in one go:
    $post_tags_arr = (array)$xml->tag;
    print_r($post_tags_arr);
    
    Array
    (
        [0] => tag1
        [1] => tag2
        [2] => tag3
    )