为了账号安全,请及时绑定邮箱和手机立即绑定

PHP - file_get_contents 无法打开流:即使文件路径正确,也没有这样的文件或目录

PHP - file_get_contents 无法打开流:即使文件路径正确,也没有这样的文件或目录

PHP
慕妹3146593 2023-12-15 10:39:44
我正在尝试使用 PHP 获取文件的内容。然后将其添加到新文件中。我正在使用 file_get_contents() 但它显示错误:PHP Warning:  file_get_contents(./home-starter.php): failed to open stream: No such file or directory尽管路径是正确的。两个文件位于同一文件夹中。Main Folder   errorfile.php   home-starter.php有什么建议么?<?phprequire_once('private/initialize.php');$city = 'Lahore';$keyword = 'Homemade Food';$areas = ['DHA', 'Bahria Town', 'Cantt', 'Gulberg', 'Valencia Town', 'Sui Gas Housing Society', 'Izmir Town', 'Faisal Town', 'Garden Town', 'Johar Town', 'Punjab Housing Society', 'Canal Housing Societies', 'State Life Housing Society', 'Model Town', 'Liaqatabad', 'Rehmanpura', 'Samanabad', 'Muslim Town', 'Town Ship', 'Iqbal Town', 'Ferozepure Road', 'Multan Road', 'Baghbanpura', 'Mughalpura', 'Walton'];foreach ($areas as $area) {  $permalink = strtolower(str_replace(' ', '-', $keyword)) . '-' . strtolower(str_replace(' ', '-', $area)) . '-' . strtolower($city);  $page_title = 'Homemade Food Delivery - Lunch Dinner - ' . $area . ' - ' . $city;  $meta_desc = 'Lunch.pk is Pakistan #1 website to order homemade food in ' . $area . ' ' . $city . '. You get tasty and healthy food cooked and delivered by families near you.';  $location = $area . ' ' . $city;  $filename = $permalink . '.php';  $content = file_get_contents( __DIR__ . '/home-starter.php');  $content = str_replace('[page-title]', $page_title, $content);  $content = str_replace('[meta-desc]', $meta_desc, $content);  $content = str_replace('[location]', $location, $content);  $is_file_created = file_put_contents($filename, $content);  if (!$is_file_created) {    echo 'Err';    break;  }}
查看完整描述

4 回答

?
互换的青春

TA贡献1797条经验 获得超6个赞

检查文件是否存在然后



$file=__DIR__ . '/home-starter.php'; 

if(file_exists($file))

{

   $content=file_get_contents($file);

}

找不到正确的路径,请使用getcwd()函数获取当前工作目录


例如,您的项目具有以下结构


文件夹

应用程序

模型 ->模型.php

其他文件夹

配置->config.php

假设您将在任何地方获取 config.php 的内容,您应该使用以下代码



$content=file_get_contents(getcwd().'/config/config.php');


查看完整回答
反对 回复 2023-12-15
?
鸿蒙传说

TA贡献1865条经验 获得超7个赞

在本地开发计算机上成功运行脚本后实施 cronjob 时,我遇到了这个问题。

我的解决方案是使用file_get_contents的第二个函数参数,将 $use_include_path 设置为TRUE

$currentFile = file_get_contents($fileinfo->getFilename(),true);


查看完整回答
反对 回复 2023-12-15
?
慕容森

TA贡献1853条经验 获得超18个赞

您需要使用物理网址

./home-starter.php

例如file_get_contents('C:\xampp\htdocs\project1\home-starter.php');


查看完整回答
反对 回复 2023-12-15
?
狐的传说

TA贡献1804条经验 获得超3个赞

检查您的 PHP 版本支持__DIR__,我能够在 PHP 7.4.24 上通过非常类似的方法获取文件内容,但我使用了一个返回内容的函数。


$content = get_file_data("myfile.txt");


function get_file_data($filename) {

    $data = file_get_contents(__DIR__ . "/$filename");


    return $data;

}


查看完整回答
反对 回复 2023-12-15
  • 4 回答
  • 0 关注
  • 67 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信