0

I'd like to be able to take in a file in PHP

**example_file.txt**
United States
Canada
-----------------------
Albania
Algeria
American Samoa
Andorra
Angola

and wrap these individual linebreaks in an HTML element that I pass it.

Example:

magicHtmlGenerator(example_file.txt, '<li>') 
// spits out <li>United States</li><li>Canada</li> etc
Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
Derek Adair
  • 21,846
  • 31
  • 97
  • 134

5 Answers5

2
function magicHtmlGenerator($filename, $wrapper) {
    $x = file_get_contents($filename);
    return '<'.$wrapper.'>'.str_replace("\n",'</'.$wrapper.'><'.$wrapper.'>',$x).'</'.$wrapper.'>';
}

$html = magicHtmlGenerator('example_file.txt','li');
echo $html;
Mark Baker
  • 209,507
  • 32
  • 346
  • 385
1

Load the file in and then use a regular expression to do the replacement.

preg_replace  ( \\r+([^\r]+)\r+\g  , \<li>$1</li>  ,  $str );

http://php.net/manual/en/function.preg-replace.php

Razor Storm
  • 12,167
  • 20
  • 88
  • 148
0

Create a function which takes those two arguments, loads the lines (can be done easily via the file function), then iterate over them appending them to a string, padded with the HTML tag you want.

Jani Hartikainen
  • 42,745
  • 10
  • 68
  • 86
0

Here's another way:

$sxml = new SimpleXMLElement('<ul></ul>', LIBXML_NOXMLDECL);
$data = file('example_file.txt', FILE_IGNORE_NEW_LINES);
foreach ($data as $line) {
    if (ctype_alpha($line)) {   // Or whatever test you need
        $sxml->addChild('li', $line);
    }
}
echo $sxml->asXML();

Output:

  • Canada
  • Albania
  • Algeria
  • Andorra
  • Angola
GZipp
  • 5,386
  • 1
  • 22
  • 18
0

No offence, but it sounds like you are trying to reinvent the wheel. Unless you find that an interesting coding exeercise, why not use of the emany templating systems out there? (hint: Smarty) That would leave your time free for "more important stuff".

Mawg says reinstate Monica
  • 38,334
  • 103
  • 306
  • 551