Forcing a SimpleXML Object to a string, regardless

2019-01-01 13:34发布

Let's say I have some XML like this

<channel>
  <item>
    <title>This is title 1</title>
  </item>
</channel>

The code below does what I want in that it outputs the title as a string

$xml = simplexml_load_string($xmlstring);
echo $xml->channel->item->title;

Here's my problem. The code below doesn't treat the title as a string in that context so I end up with a SimpleXML object in the array instead of a string.

$foo = array( $xml->channel->item->title );

I've been working around it like this

$foo = array( sprintf("%s",$xml->channel->item->title) );

but that seems ugly.

What's the best way to force a SimpleXML object to a string, regardless of context?

10条回答
长期被迫恋爱
2楼-- · 2019-01-01 13:55

Try strval($xml->channel->item->title)

查看更多
谁念西风独自凉
3楼-- · 2019-01-01 14:02

The following is a recursive function that will typecast all single-child elements to a String:

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// FUNCTION - CLEAN SIMPLE XML OBJECT
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function cleanSimpleXML($xmlObject = ''){

    // LOOP CHILDREN
    foreach ($xmlObject->children() as $child) {

        // IF CONTAINS MULTIPLE CHILDREN
        if(count($child->children()) > 1 ){

            // RECURSE
            $child = cleanSimpleXML($child);

        }else{

            // CAST
            $child = (string)$child;

        }

    }

    // RETURN CLEAN OBJECT
    return $xmlObject;

} // END FUNCTION
查看更多
几人难应
4楼-- · 2019-01-01 14:07

Not sure if they changed the visibility of the __toString() method since the accepted answer was written but at this time it works fine for me:

var_dump($xml->channel->item->title->__toString());

OUTPUT:

string(15) "This is title 1"
查看更多
伤终究还是伤i
5楼-- · 2019-01-01 14:08

There is native SimpleXML method SimpleXMLElement::asXML Depending on parameter it writes SimpleXMLElement to xml 1.0 file or just to a string:

$xml = new SimpleXMLElement($string);
$validfilename = '/temp/mylist.xml';
$xml->asXML($validfilename);    // to a file
echo $xml->asXML();             // to a string
查看更多
登录 后发表回答