如何将XML的内容作为字符串获取? 我有一个像这样的xml:
<?xml version="1.0" encoding="utf-8"?>
<section>
<paragraph>some content</paragraph>
<custom>some more content</custom>
</section>
我希望将section的内容作为字符串,如下所示:
<paragraph>some content</paragraph>
<custom>some more content</custom>
到目前为止我读到的每个文档只解释了如何获取子节点的内容而不是根节点的内容。
答案 0 :(得分:0)
您可以使用xml解析器创建数组并使用它。例如:
<?php
$xml = <<<XML
<?xml version="1.0" encoding="utf-8"?>
<section>
<paragraph>some content</paragraph>
<custom>some more content</custom>
</section>
XML;
$values = [];
$p = xml_parser_create();
xml_parser_set_option($p, XML_OPTION_CASE_FOLDING, 0);
xml_parse_into_struct($p, $xml, $values);
xml_parser_free($p);
var_dump($values);
答案 1 :(得分:0)
可以使用DOMDocument实现(按here查看实际操作)
$xmlStr = '<?xml version="1.0" encoding="utf-8"?>
<section>
<paragraph>some content</paragraph>
<custom>some more content</custom>
</section>
';
$xml = new DOMDocument();
$xml->loadXML($xmlStr);
if($xml->childNodes->length > 0) {
foreach($xml->childNodes->item(0)->childNodes as $rootChildNode){
echo $xml->saveXML($rootChildNode);
}
}