无论上下文如何,都将SimpleXML对象强制为字符串
题
假设我有一些这样的XML
<channel>
<item>
<title>This is title 1</title>
</item>
</channel>
下面的代码实现我想要的,它将标题输出为字符串
$xml = simplexml_load_string($xmlstring);
echo $xml->channel->item->title;
这是我的问题。下面的代码不会将标题视为该上下文中的字符串,因此我最终在数组中使用SimpleXML对象而不是字符串。
$foo = array( $xml->channel->item->title );
我一直在努力解决这个问题
$foo = array( sprintf("%s",$xml->channel->item->title) );
但这看起来很难看。
无论上下文如何,将SimpleXML对象强制转换为字符串的最佳方法是什么?
解决方案
将SimpleXMLObject强制转换为字符串:
$foo = array( (string) $xml->channel->item->title );
上面的代码在SimpleXMLObject上内部调用 __ toString()
。此方法不公开,因为它会干扰SimpleXMLObject的映射方案,但仍可以上述方式调用它。
其他提示
您可以使用PHP函数
strval();
此函数返回传递给它的参数的字符串值。
有原生的SimpleXML方法 SimpleXMLElement :: asXML 根据参数,它将SimpleXMLElement写入xml 1.0文件或仅写入字符串:
$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-&gt;通过每个级别,直到你得到你想要的 您也可以将所有节点放入一个没有级别或的数组中 几乎任何你想要的方式。
接受的答案实际上返回一个包含字符串的数组,这不完全是OP请求的字符串(字符串)。 要扩展该答案,请使用:
$foo = [ (string) $xml->channel->item->title ][0];
返回数组的单个元素,即字符串。
尝试strval($ xml-&gt; channel-&gt; item-&gt; title)
不确定他们是否更改了 __ toString()
方法的可见性,因为已经接受了答案,但此时它对我来说很好:
var_dump($xml->channel->item->title->__toString());
<强>输出:强>
string(15) "This is title 1"
有原生的SimpleXML方法SimpleXMLElement :: asXML根据参数,它将SimpleXMLElement写入xml 1.0文件,是
$get_file= read file from path;
$itrate1=$get_file->node;
$html = $itrate1->richcontent->html;
echo $itrate1->richcontent->html->body->asXML();
print_r((string) $itrate1->richcontent->html->body->asXML());
以下是一个递归函数,它将所有单子元素强制转换为 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