问题
I'm trying to convert lines in an XML node into an unordered list, however I'm having some difficulty.
Take for example this node :
<test>
Line1
Line2
Line3
</test>
I would like to transform it into this with PHP
<ul>
<li>Line1</li>
<li>Line2</li>
<li>Line3</li>
</ul>
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
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?
Thanks.
回答1:
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>';
来源:https://stackoverflow.com/questions/19325893/preserving-line-breaks-in-xml-node