0

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.

Shane
  • 205
  • 1
  • 9

1 Answers1

2

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>';
George Brighton
  • 5,131
  • 9
  • 27
  • 36
  • 1
    ...You're right, it works, thank you. Such a small oversight caused me so much trouble, I'll begin kicking myself now. – Shane Oct 11 '13 at 19:48