自定义数组格式化输出函数(dump),调试程序时很有用
发布时间:2015-10-14, 15:14:24 分类:PHP | 编辑 off 网址 | 辅助
正文 3019字数 588,369阅读
前面我们谈了一下关于判断远程文件是否存在的一个函数,希望大家能够记下来,因为在最近这几篇文章中这几个函数会联合一起使用,将来这些函数也会被我使用到改写的MG2程序里。下面说说今天要说的这个自定义函数dump,该函数是我从网上搜集下来的,作用为将一个数组进行格式化输出,对于我来说要看php中一个数组的内容是很费力的,因为本人的php可以说是无基础可言,用到哪里就看哪里,呵呵,完全的现用现学。搜到这个函数后,发现通过格式化输出后,再去看某一个数组时确实省事多了,经过测试,暂无发现什么问题,下面给出该函数代码:
function dump($vars, $label = '', $return = false) {
if (ini_get('html_errors')) {
$content = "\n";
if ($label != '') {
$content .= "<strong>{$label} :</strong>\n";
}
$content .= htmlspecialchars(print_r($vars, true));
$content .= "\n
\n";
} else {
$content = $label . " :\n" . print_r($vars, true);
}
if ($return) { return $content; }
echo $content;
return null;
}
Run code
Cut to clipboard
以上代码为原文,未经修改,可以正常使用,下面给出一个例程,和输出结果,通过这个函数,我们在写一些php代码时,在调试阶段就可以很清楚的查到数组内容了,例程中应用到了本函数及前面讲的判断远程文件是否存在的函数remote_file_exists以及get_headers函数,例程及输出结果如下:
function dump($vars, $label = '', $return = false) {
if (ini_get('html_errors')) {
$content = "\n";
if ($label != '') {
$content .= "<strong>{$label} :</strong>\n";
}
$content .= htmlspecialchars(print_r($vars, true));
$content .= "\n
\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
//)
Run code
Cut to clipboard
(支付宝)给作者钱财以资鼓励 (微信)→
有过 3 条评论 »
echo "<pre>"; print_r($res); echo "</pre>";
如果你想完全保留原有数组并只想新的数组附加到后面,用 + 运算符:
<?php $array1 = array(); $array2 = array(1 => "data"); $result = $array1 + $array2; ?>
数字键名将被保留从而原来的关联保持不变。
//打印输出数组信息 function printf_info($data) { foreach($data as $key=>$value){ echo "<font color='#00ff55;'>$key</font> : $value <br/>"; } }