问题描述
我试图将XML节点中的行转换为无序列表,但是我遇到了一些困难。
I'm trying to convert lines in an XML node into an unordered list, however I'm having some difficulty.
以该节点为例:
<test>
Line1
Line2
Line3
</test>
我想用PHP将其转换为它
I would like to transform it into this with PHP
<ul>
<li>Line1</li>
<li>Line2</li>
<li>Line3</li>
</ul>
我尝试使用DOMDocument和SimpleXML,但是似乎都没有保留换行符。当回显时,节点值如下所示:
I've tried using DOMDocument and SimpleXML, however neither seem to retain the newlines. When echoed, the node value looks like this :
Line1 Line2 Line3
我还尝试了 explode
以便使包含每行作为元素的数组:
I've also tried explode
in order to have an array containing each line as an element :
$lines = explode( '\n', $node->nodeValue);
但是,它只返回一个元素的数组,所以我不能用
However, it only returns an array with one element, so I can't make an unordered list with it.
我有一种简单的方法吗?
Is there a simple way for me to do this?
谢谢。
推荐答案
您会踢自己。 ’\n’
应该是 \n
!这是一个完整的示例:
You're going to kick yourself. '\n'
should be "\n"
! Here's a full example:
$Dom = new DOMDocument('1.0', 'utf-8');
$Dom->loadXML(
'<test>
Line1
Line2
Line3
</test>');
$value = $Dom->documentElement->nodeValue;
$lines = explode("\n", $value);
$lines = array_map('trim', $lines); // remove leading and trailing whitespace
$lines = array_filter($lines); // remove empty elements
echo '<ul>';
foreach($lines as $line) {
echo '<li>', htmlentities($line), '</li>';
}
echo '</ul>';
这篇关于在xml节点中保留换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!