如何获取 XML 节点的内容作为文本
How to get the content of a XML node as text
<?php
$string = <<<XML
<a>
<y>
This is <b>text</b>
<c>stuff</c>
</y>
<d>
This is super <em>code</em>, and we like it ! <b>FOObarr</b> !
</d>
</a>
XML;
$xml = new SimpleXMLElement($string);
foreach ($xml as $node) {
//use another function than asXML, to get some more magic
echo $node->asXML();
echo "\n--\n";
}
?>
我要输出这个:
This is <b>text</b>
<c>stuff</c>
--
This is super <em>code</em>, and we like it ! <b>FOObarr</b> !
--
没有y标签和d标签;但是当前代码输出这个:
<y>
This is <b>text</b>
<c>stuff</c>
</y>
--
<d>
This is super <em>code</em>, and we like it ! <b>FOObarr</b> !
</d>
--
请注意,根据输入数据,标签的命名可能会有所不同。
正如@iainn 所说,您将 html 嵌入到 XML 中而不对其进行编码,因此它会变得有点混乱。但是根据您的示例,您可以在回显之前更深入地导航一个级别,因为 HTML 看起来像 XML 到解码器。
<?php
$string = <<<XML
<a>
<y>
This is <b>text</b>
<c>stuff</c>
</y>
<d>
This is super <em>code</em>
</d>
</a>
XML;
$xml = new SimpleXMLElement($string);
foreach ($xml as $node) {
echo $node;
foreach($node as $subnode) {
echo $subnode->asXml();
}
echo "\n--\n";
}
?>
产生:
This is
<b>text</b><c>stuff</c>
--
This is super
<em>code</em>
--
如果在实践中您的数据有点复杂,或者换行符和其他细微之处很重要,请考虑对 HTML.
进行编码
<?php
$string = <<<XML
<a>
<y>
This is <b>text</b>
<c>stuff</c>
</y>
<d>
This is super <em>code</em>, and we like it ! <b>FOObarr</b> !
</d>
</a>
XML;
$xml = new SimpleXMLElement($string);
foreach ($xml as $node) {
$s = trim($node->asXML());
$s = preg_replace(['#^<[^>]*>#','#<[^>]*>$#'], '', $s);
$s = trim($s);
echo $s;
echo "\n--\n";
}
?>
<?php
$string = <<<XML
<a>
<y>
This is <b>text</b>
<c>stuff</c>
</y>
<d>
This is super <em>code</em>, and we like it ! <b>FOObarr</b> !
</d>
</a>
XML;
$xml = new SimpleXMLElement($string);
foreach ($xml as $node) {
//use another function than asXML, to get some more magic
echo $node->asXML();
echo "\n--\n";
}
?>
我要输出这个:
This is <b>text</b>
<c>stuff</c>
--
This is super <em>code</em>, and we like it ! <b>FOObarr</b> !
--
没有y标签和d标签;但是当前代码输出这个:
<y>
This is <b>text</b>
<c>stuff</c>
</y>
--
<d>
This is super <em>code</em>, and we like it ! <b>FOObarr</b> !
</d>
--
请注意,根据输入数据,标签的命名可能会有所不同。
正如@iainn 所说,您将 html 嵌入到 XML 中而不对其进行编码,因此它会变得有点混乱。但是根据您的示例,您可以在回显之前更深入地导航一个级别,因为 HTML 看起来像 XML 到解码器。
<?php
$string = <<<XML
<a>
<y>
This is <b>text</b>
<c>stuff</c>
</y>
<d>
This is super <em>code</em>
</d>
</a>
XML;
$xml = new SimpleXMLElement($string);
foreach ($xml as $node) {
echo $node;
foreach($node as $subnode) {
echo $subnode->asXml();
}
echo "\n--\n";
}
?>
产生:
This is
<b>text</b><c>stuff</c>
--
This is super
<em>code</em>
--
如果在实践中您的数据有点复杂,或者换行符和其他细微之处很重要,请考虑对 HTML.
进行编码<?php
$string = <<<XML
<a>
<y>
This is <b>text</b>
<c>stuff</c>
</y>
<d>
This is super <em>code</em>, and we like it ! <b>FOObarr</b> !
</d>
</a>
XML;
$xml = new SimpleXMLElement($string);
foreach ($xml as $node) {
$s = trim($node->asXML());
$s = preg_replace(['#^<[^>]*>#','#<[^>]*>$#'], '', $s);
$s = trim($s);
echo $s;
echo "\n--\n";
}
?>