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

5 Answers 5

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;
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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.

Comments

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.