Generate HTML given a text file organized with carriage returns in PHP
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
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;
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
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.
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
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".
精彩评论