无论上下文如何,都将SimpleXML对象强制转换为string

比方说,我有这样的XML

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

下面的代码做我想要的,它输出标题作为一个string

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

这是我的问题。 下面的代码不会将该标题看作是该上下文中的string,所以我最终将在数组中使用SimpleXML对象而不是string。

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

我一直在这样做

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

但这似乎是丑陋的。

无论上下文如何,将SimpleXML对象强制为string的最佳方式是什么?

将SimpleXMLObjecttypes转换为string:

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

上面的代码在内部调用SimpleXMLObject上的__toString() 。 这个方法不是公开的,因为它干扰了SimpleXMLObject的映射scheme,但是它仍然可以以上述方式调用。

你可以使用PHP函数

 strval(); 

该函数返回传递给它的参数的string值。

有原生的SimpleXML方法SimpleXMLElement :: asXML根据参数,它将SimpleXMLElement写入xml 1.0文件或只写入一个string:

 $xml = new SimpleXMLElement($string); $validfilename = '/temp/mylist.xml'; $xml->asXML($validfilename); // to a file echo $xml->asXML(); // to a string 

另一个丑陋的做法是:

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

它的工作原理,但并不漂亮。

要将XML数据导入到一个php数组中,请执行以下操作:

 // this gets all the outer levels into an associative php array $header = array(); foreach($xml->children() as $child) { $header[$child->getName()] = sprintf("%s", $child); } echo "<pre>\n"; print_r($header); echo "</pre>"; 

要得到一个孩子的孩子,然后只是这样做:

 $data = array(); foreach($xml->data->children() as $child) { $header[$child->getName()] = sprintf("%s", $child); } echo "<pre>\n"; print_r($data); echo "</pre>"; 

您可以展开$ xml->通过每个级别,直到您得到您想要的还可以将所有节点放入一个数组中,而不需要任何级别或任何您想要的方式。

被接受的答案实际上返回一个包含一个string的数组,这不正是OP所要求的(一个string)。 要扩大这个答案,请使用:

 $foo = [ (string) $xml->channel->item->title ][0]; 

它返回数组的单个元素,一个string。

尝试strval($ xml-> channel-> item-> title)

下面是一个recursion函数,将所有的单个子元素绑定到一个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 

不知道是否他们改变了__toString()方法的可见性,因为接受的答案已经写好了,但在这个时候对我来说工作正常:

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

OUTPUT:

 string(15) "This is title 1"