【问题标题】:PHP: Warning: file_get_contents(): Filename cannot be empty inPHP:警告:file_get_contents():文件名不能为空
【发布时间】:2014-07-16 19:31:09
【问题描述】:

我正在我的服务器上尝试这个新脚本,但我似乎无法弄清楚为什么它总是给我以下错误:

警告:file_get_contents():第 51 行 /includes/classes/spin_article.php 中的文件名不能为空

这一行给出了错误 --> $string = file_get_contents($files[rand(1, count($files)) -1]);

<?PHP
class Spintax
{
    public function process($text)
    {
        return preg_replace_callback(
            '/\{(((?>[^\{\}]+)|(?R))*)\}/x',
            array($this, 'replace'),
            $text
        );
    }

    public function replace($text)
    {
        $text = $this->process($text[1]);
        $parts = explode('|', $text);
        return $parts[array_rand($parts)];
    }
}
?>

<?PHP
ob_start();
$files = glob("spintax_articles/*.txt");
$spintax = new Spintax();
$string = file_get_contents($files[rand(1, count($files)) -1]);
echo $spintax->process($string);
$page = ob_get_contents();
ob_end_flush();
$fp = fopen("content.txt","w");
fwrite($fp,$page);
fclose($fp);
?>

【问题讨论】:

  • 继续print_r($files),您会在 glob 中找到一个不是文件的值。
  • $files[rand(1, count($files)) -1] 显然没有任何价值。在尝试使用它们之前,您需要确保 4files 包含您期望的值。
  • 我的猜测是没有与glob匹配的文件。
  • 还有,不应该是$files[mt_rand(1, count($files)-1)]吗?

标签: php spintax


【解决方案1】:

如果确实有匹配的文件,那么您可能会得到一个比最大值大 1 的随机索引。使用:

$string = file_get_contents($files[rand(1, count($files)-1)]);

注意-1 位置。

如果没有文件,您应该使用条件检查。

<?php
$files = glob("spintax_articles/*.txt");

if(!empty($files)) {

    $spintax = new Spintax();
    $string  = file_get_contents($files[mt_rand(1, count($files)-1)]);

    $fp = fopen("content.txt", "w");
    fwrite($fp, $spintax->process($string));
    fclose($fp);
}
?>

【讨论】:

  • 关于-1 位置,这不是给您相同的上限值但下限值1,这意味着您永远不会选择数组的第一项? OP 的版本对我来说很好。
  • 或者只是file_get_contents($files[array_rand($files)]);,但我已经破坏了你的回答太多了;p
猜你喜欢
  • 1970-01-01
  • 2014-01-31
  • 1970-01-01
  • 1970-01-01
  • 2013-03-19
  • 1970-01-01
  • 1970-01-01
  • 2012-05-24
  • 2013-06-18
相关资源
最近更新 更多