1. 程式人生 > >最精簡高效的PHP陣列轉HTML程式碼的方法array2html

最精簡高效的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>


此文屬個人原創,轉載請註明來源!