views:

50

answers:

5

sorry for the title... kind of lame...

but anyways 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.

EX: magicHtmlGenerator(example_file.txt, '<li>') // spits out <li>United States</li><li>Canada</li> etc

A: 

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
+1  A: 

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
+2  A: 
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
A: 

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
A: 

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".

LeonixSolutions