以前习惯用 echo,print_r 等方法来测试php输出,这样多多少少会影响到代码的正常运行,现改成“把测试变量输出到文本”的形式,可实现日志形式的调试,如接口服务端调试。代码如下:
- <?php
- /**
- * 写文件函数
- * @param string $filename 文件名
- * @param string $writetext 要写入的文本字符串
- * @param string $openmod 文本写入模式('w':覆盖重写,'a':文本追加)
- * @return boolean
- */
- function new_writefile($filename, $writetext, $openmod = 'w') {
- if (@$fp = fopen($filename, $openmod)) {
- flock($fp, 2);
- fwrite($fp, $writetext);
- fclose($fp);
- return true;
- } else {
- return false;
- }
- }
- /**
- * 将“数组”转换成“数组字符串”(方便写入文本)
- * @param array $array 要转换的数组
- * @param int $level 转换级别/深度
- */
- function new_arr2str($array, $level = 0) {
- $space = '';
- for ($i = 0; $i <= $level; $i++) {
- $space .= "\t";
- }
- $evaluate = "Array\n$space(\n";
- $comma = $space;
- foreach ($array as $key => $val) {
- $key = is_string($key) ? '\''.addcslashes($key, '\'\\').'\'' : $key;
- $val = !is_array($val) && (!preg_match("/^\-?\d+$/", $val) || strlen($val) > 12 || substr($val, 0, 1)=='0') ? '\''.addcslashes($val, '\'\\').'\'' : $val;
- if (is_array($val)) {
- $evaluate .= "$comma$key => " . new_arr2str($val, $level + 1);
- } else {
- $evaluate .= "$comma$key => $val";
- }
- $comma = ",\n$space";
- }
- $evaluate .= "\n$space)";
- return $evaluate;
- }
- /**
- * 写数组(其实用下面的“write函数”就足够用啦~~~)
- * @param array $array 要写入的数组
- * @param string $type 文本写入类型('w':覆盖重写,'a':文本追加)
- */
- function writeArr($array, $type = 'w') {
- $filename = 'd:\php\wamp\www\write.txt';
- $writetext = test_arr2str($array);
- new_writefile($filename, $writetext, $type);
- }
- /**
- * 写对象(包括 数字、字符串、数组)
- * @param string $writetext 要写入的文本字符串
- * @param string $type 文本写入类型('w':覆盖重写,'a':文本追加)
- */
- function write($writetext, $type = 'a'){ // 'w':覆盖重写,'a':表示'文本追加'
- $filename = 'd:\php\wamp\www\write.txt';
- $writetext = "++++++++++++++++++++++++++++++++++++++++++\r\n" . print_r($writetext, true) . "\r\n";
- new_writefile($filename, $writetext, $type);
- }
- //require_once('d:\php\wamp\www\write.php'); // add by wenjb(注意:本地测试用,不用提交到 svn)
应用如下:
- $arr = array(
- "w" => "wen",
- "j" => "jian",
- "b" => "bao"
- );
- write($arr);
输出结果如下:
- ++++++++++++++++++++++++++++++++++++++++++
- Array
- (
- [w] => wen
- [j] => jian
- [b] => bao
- )
上面的仅仅是小技巧而已,最好还是用专业的调试工具去调试比较好。。。也可以
- $data222 = $arr;
- $text222 = print_r($data222, true);
- $filename222 = 'd:\My Documents\1\write.txt';
- file_put_contents($filename222, $text222);
时间: 2024-12-04 01:57:48