从文本文件在php中打开变量

时间:2019-05-08 16:38:36

标签: php

我想用困难的方式复制一些文件(不要问为什么它太复杂了),并使用创建到文件的变量并从另一个脚本打开它,然后启动应对措施

我已经创建了一个功能页面,该页面保存了我现在想要的值,我有了这段代码,我要提取名为tmpCraft.txt的文件中的变量,然后将其从tmp文件复制到目标文件中所以这是我的代码,其名称为accountCrafter.php

<?php

$dst = fopen("tmpCraft.txt", "r") or die("Unable to open file!");   
echo fread($dst,filesize("tmpCraft.txt"));  
fclose($dst);

$file = 'structure/index.html';

if (!copy($file, $dst . "/index.html")) {
    echo "failed to copy $file...\n"; 
}else{
    echo "copied $file into $newfile\n"; 
}

?>

我运行了它,结果就是这样:

  

noni
  警告:copy(资源ID#3 / index.html)[function.copy]:无法打开流:第9行的H:\ xampp \ htdocs \ dev4 \ test2 \ accountCrafter.php中没有这样的文件或目录
  无法复制structure / index.html ...

值为noni

由于某种原因,它将值提取为

2 个答案:

答案 0 :(得分:1)

这可能是您想要的:

<?php
$dst = trim(file_get_contents("tmpCraft.txt"));
$file = 'structure/index.html';
$newfile = $dst . "/index.html";

if (!copy($file, $newfile)) {
    echo "failed to copy $file...\n"; 
}else{
    echo "copied $file into $newfile\n"; 
}

?>

您需要将$dst设置为文件的内容,而不是文件句柄。 trim()将删除文件名称周围的所有多余空格。

答案 1 :(得分:0)

Barmar是正确的,他的代码可以正常工作,但是我在创建文件时犯了一个错误,它添加了整行,这样就可以了

最终代码

<?php
$dst = trim(file_get_contents("tmpCraft.txt"));
$file = 'structure/index.html';
$newfile = trim($dst) . "/index.html";

if (!copy($file, $newfile)) {
    echo "failed to copy $file...\n"; 
}else{
    echo "copied $file into $newfile\n"; 
}

?>