Preserving line breaks in xml node

ぐ巨炮叔叔 提交于 2019-12-25 01:48:55

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!