自定义数组格式化输出函数(dump),调试程序时很有用
前面我们谈了一下关于判断远程文件是否存在的一个函数,希望大家能够记下来,因为在最近这几篇文章中这几个函数会联合一起使用,将来这些函数也会被我使用到改写的MG2程序里。
下面说说今天要说的这个自定义函数dump,该函数是我从网上搜集下来的,作用为将一个数组进行格式化输出,对于我来说要看php中一个数组的内容是很费力的,因为本人的php可以说是无基础可言,用到哪里就看哪里,呵呵,完全的现用现学。搜到这个函数后,发现通过格式化输出后,再去看某一个数组时确实省事多了,经过测试,暂无发现什么问题,下面给出该函数代码:
- function dump($vars, $label = '', $return = false) {
- if (ini_get('html_errors')) {
- $content = "<pre>\n";
- if ($label != '') {
- $content .= "<strong>{$label} :</strong>\n";
- }
- $content .= htmlspecialchars(print_r($vars, true));
- $content .= "\n</pre>\n";
- } else {
- $content = $label . " :\n" . print_r($vars, true);
- }
- if ($return) { return $content; }
- echo $content;
- return null;
- }
以上代码为原文,未经修改,可以正常使用,下面给出一个例程,和输出结果,通过这个函数,我们在写一些php代码时,在调试阶段就可以很清楚的查到数组内容了,例程中应用到了本函数及前面讲的判断远程文件是否存在的函数remote_file_exists以及get_headers函数,例程及输出结果如下:
- function dump($vars, $label = '', $return = false) {
- if (ini_get('html_errors')) {
- $content = "<pre>\n";
- if ($label != '') {
- $content .= "<strong>{$label} :</strong>\n";
- }
- $content .= htmlspecialchars(print_r($vars, true));
- $content .= "\n</pre>\n";
- } else {
- $content = $label . " :\n" . print_r($vars, true);
- }
- if ($return) { return $content; }
- echo $content;
- return null;
- }
- function remote_file_exists($url_file){
- $url_file = trim($url_file);
- if (empty($url_file)) return false;
- $url_arr = parse_url($url_file);
- if (!is_array($url_arr) || empty($url_arr)) return false;
- $host = $url_arr['host'];
- $path = $url_arr['path'] ."?".$url_arr['query'];
- $port = isset($url_arr['port']) ?$url_arr['port'] : "80";
- $fp = fsockopen($host, $port, $err_no, $err_str,30);
- if (!$fp) return false;
- $request_str = "GET ".$path." HTTP/1.1\r\n";
- $request_str .= "Host:".$host."\r\n";
- $request_str .= "Connection:Close\r\n\r\n";
- fwrite($fp,$request_str);
- $first_header = fread($fp, 128);
- fclose($fp);
- if (trim($first_header) == "") return false;
- if (!preg_match("/200/", $first_header) || preg_match("/Location:/", $first_header)) return false;
- return true;
- }
- $url = "http://image.verylifes.com/webimages/78620c944c3a_9B13/201008230321.jpg";
- if (remote_file_exists($url)) {
- $headInf = get_headers($url,1);
- dump($headInf);
- }
- //输出结果
- //Array
- //(
- // [0] => HTTP/1.1 200 OK
- // [Date] => Thu, 26 Aug 2010 02:51:07 GMT
- // [Server] => Apache
- // [Last-Modified] => Mon, 23 Aug 2010 03:01:54 GMT
- // [ETag] => "20a9e05-e220-4c71e4a2"
- // [Accept-Ranges] => bytes
- // [Content-Length] => 57888
- // [Connection] => close
- // [Content-Type] => image/jpeg
- //)

最新评论