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

目前网络上常规的 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>


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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值