有没有从PHP生成字符串的函数SimpleXMLElement
?
Answers:
您可以使用该SimpleXMLElement::asXML()
方法来完成此操作:
$string = "<element><child>Hello World</child></element>";
$xml = new SimpleXMLElement($string);
// The entire XML tree as a string:
// "<element><child>Hello World</child></element>"
$xml->asXML();
// Just the child node as a string:
// "<child>Hello World</child>"
$xml->child->asXML();
$string = $xml->child->__toString();
这是我为解决此问题而编写的函数(假设标签没有属性)。此函数将在节点中保留HTML格式:
function getAsXMLContent($xmlElement)
{
$content=$xmlElement->asXML();
$end=strpos($content,'>');
if ($end!==false)
{
$tag=substr($content, 1, $end-1);
return str_replace(array('<'.$tag.'>', '</'.$tag.'>'), '', $content);
}
else
return '';
}
$string = "<element><child>Hello World</child></element>";
$xml = new SimpleXMLElement($string);
echo getAsXMLContent($xml->child); // prints Hello World
有时您可以简单地键入:
// this is the value of my $xml
object(SimpleXMLElement)#10227 (1) {
[0]=>
string(2) "en"
}
$s = (string) $xml; // returns "en";
$xmlitem->description
。谢谢。