【问题标题】:PHP: Call to undefined function echocsv()PHP:调用未定义的函数 echocsv()
【发布时间】:2014-09-17 09:49:53
【问题描述】:

我正在尝试运行以下代码

$query = sprintf('SELECT * FROM custfail');
$result = mysql_query($query, $conn) or die(mysql_error($conn));

/*
 * send response headers to the browser
 * following headers instruct the browser to treat the data as a csv file called export.csv
 */

header('Content-Type: text/csv');
header('Content-Disposition: attachment;filename=custfail.csv');

/*
 * output header row (if atleast one row exists)
 */

$row = mysql_fetch_assoc($result);
if ($row) {
    echocsv(array_keys($row));
}

/*
 * output data rows (if atleast one row exists)
 */

while ($row) {
    echocsv($row);
    $row = mysql_fetch_assoc($result);
}

/*
 * echo the input array as csv data maintaining consistency with most CSV implementations
 * - uses double-quotes as enclosure when necessary
 * - uses double double-quotes to escape double-quotes 
 * - uses CRLF as a line separator
 */

function echocsv($fields)
{
    $separator = '';
    foreach ($fields as $field) {
        if (preg_match('/\\r|\\n|,|"/', $field)) {
            $field = '"' . str_replace('"', '""', $field) . '"';
        }
        echo $separator . $field;
        $separator = ',';
    }
    echo "\r\n";

当我运行代码时,我得到一个包含以下错误的 CSV 文件

<b>Fatal error</b>:  Call to undefined function echocsv() in <b>*snip*</b> on line <b>31</b><br />

行号与发布的代码无关,因为我删除了一些以前的代码(密码检查 if 语句(嵌入此代码)和 SQL 连接详细信息),但在调用此函数时发生,

$row = mysql_fetch_assoc($result);
if ($row) {
    echocsv(array_keys($row));
}

有谁能给我指出正确的方向

【问题讨论】:

  • 尝试将你的函数移到页面顶部
  • 函数结束后缺少} 可能是问题所在。尽管如果那是您使用的实际代码,我希望 PHP 会引发解析错误。
  • @RamSharma 不,它不是 - ifforeach 有结束标签,而不是函数本身。
  • 函数需要在调用之前,PHP从上到下执行它的脚本。
  • @ɴᴀᴛʜ 我同意,如果函数未关闭,则错误将是解析错误。在这种情况下,他必须将他的功能移到页面顶部

标签: php mysql fatal-error


【解决方案1】:

感谢@RamSharma 在他的 cmets 问题上的帮助。问题是我在页面底部有这个功能,在它被调用之后

解决方案是将函数移动到调用上方的行

【讨论】:

    【解决方案2】:

    如果您使用“原始”*.php 脚本,则需要在调用之前定义函数,基于此处的阅读:http://php.net/manual/en/functions.user-defined.php

    "函数在被引用之前不需要定义,除非函数是有条件定义的(...)"

    【讨论】:

    • 函数在被引用之前需要定义。
    • @Ja͢ck 是对的,我的错误,问题与函数被放错地方有关,因为我们在问题中缺少代码。
    猜你喜欢
    • 2015-11-18
    • 2021-06-05
    • 2013-05-19
    • 2012-04-05
    • 1970-01-01
    • 2015-09-21
    • 2017-07-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多