最精简高效的PHP数组转HTML代码的方法array2html

来源:互联网 发布:求大作战刷圣衣软件 编辑:程序博客网 时间:2024/06/04 08:04

目前网络上常规的 PHP 数组转 HTML 代码的方法都是通过循环 for 或者 foreach 来遍历数组,然后通过字符替换、正则表达式替换或者字符拼接等方法来生成 HTML 代码,为了避免使用循环而发明此方法,搜了一下目前网络上没有人尝试过这种方法,属于一次新的尝试,我把它命名为array2html。

 

Methods at present on the network PHP array of conventional HTML code is through for or foreach loop to iterate through the array, and then through the character replacement, regular expression replacement or character stitching method to generate HTML code, in order to avoid the use of the array loop and invented this method, search the Internet and no one tried this approach, is a new attempt, I named it array2html.

PHP 函数 array2html 的代码:

The source code of function 'array2html' is:

<?php/** * Replace PHP Array to HTML Code directly * @param array  $arr ref of input array data * @param string $mainTag top html tag name of output html code * @param string $listTag html tag name of each element * @author csdn_do_net_id:hpchn * @link http://blog.csdn.net/hpchn */function array2html(array &$arr, $mainTag='ul', $listTag='li'){return  strtr(var_export($arr,TRUE)  ,array(    "'," => "</$listTag>",    " => '" => '>',    '  ' => "<$listTag id=",    'array (' => "<$mainTag>",    "\n)" => "\n</$mainTag>")  );}echo array2html($_SERVER);


输出结果:

The result of output like: 

<ul><li id='SERVER_PROTOCOL'>HTTP/1.1</li><li id='GATEWAY_INTERFACE'>CGI/1.1</li><li id='SERVER_SOFTWARE'>nginx/1.5.9</li><li id='REMOTE_ADDR'>127.0.0.1</li><li id='REMOTE_PORT'>53937</li><li id='SERVER_ADDR'>127.0.0.1</li><li id='SERVER_PORT'>80</li><li id='SERVER_NAME'>localhost</li><li id='REDIRECT_STATUS'>200</li><li id='HTTP_ACCEPT'>text/html, application/xhtml+xml, */*</li><li id='HTTP_ACCEPT_LANGUAGE'>zh-CN</li><li id='HTTP_USER_AGENT'>Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)</li><li id='HTTP_ACCEPT_ENCODING'>gzip, deflate</li><li id='HTTP_HOST'>localhost</li><li id='HTTP_CONNECTION'>Keep-Alive</li></ul>


此文属个人原创,转载请注明来源!

0 0
原创粉丝点击