Search code examples
phphtmlarrayssimplexml

How to write values from SimpleXML array in input field


I have a simpleXML array called $tags that contains a list of tags which I would like to use for the default value of an input field when loading a page.

My XML (example):

Array ( [0] => SimpleXMLElement Object ( [0] => tag1 ) 
        [1] => SimpleXMLElement Object ( [0] => tag2 ) 
)

My HTML (for demonstration):

<input type="text" 
    class="form-control optional sel2" id="tags" name="tags" 
    value="<?php echo $tags; ?>" 
/>

The above is just for demonstration as I don't know what is the correct approach for this. How can I get the values from the array set as the default value for the input field so that in the above example this would show "tag1,tag2"?


Solution

  • You just need to convert the array of SimpleXMLElements into an array of strings. Then you can use it in implode().

    echo implode(',', array_map(function($tag) {
        return (string) $tag;
    }, $tags));
    

    Come to think of it, I doubt you need to map the array. Using SimpleXMLElement in implode() should implicitly convert them to strings so this should suffice...

    echo implode(',', $tags);
    

    Demo here ~ https://eval.in/187582