【问题标题】:How to assign a value to a variable from a text file? [closed]如何为文本文件中的变量赋值? [关闭]
【发布时间】:2013-12-30 14:02:50
【问题描述】:

我正在使用脚本从 ftp 备份文件。代码如下。

include "recurseZip.php";
//Source file or directory to be compressed.
$src='source/images/black.png';
//Destination folder where we create Zip file.
$dst='backup';
$z=new recurseZip();
echo $z->compress($src,$dst);

现在我想从包含文件名列表的 source/files.txt 中获取 $src 的值。

我的 .txt 文件:

index.php.bk-2013-12-02
index.php.bk-2013-12-07
index.php.bk-2013-12-10
index.php.bk-2013-12-20
index.php.bk-2013-12-26
function.php.bk-2013-12-20
function.php.bk-2013-12-23
contact.php.bk-2013-12-23
contact.php.bk-2013-12-30

我的 source/files.txt 包含 10 个文件名,这些文件名需要作为值分配给变量 $src 我正在使用此脚本 http://ramui.com/articles/php-zip-files-and-directory.html

我该怎么做?

任何帮助将不胜感激。

谢谢。

【问题讨论】:

  • “从source/files.txt获取文件名到$src”是什么意思
  • 你想只获取文件名,即 black.png 并将其分配给 $src 变量吗?
  • 你想读取一个名为 files.txt 的文件并根据它的内容给 $src 命名吗??
  • 嗨 Starr,我已经在下面给出了答案。看看吧。
  • 大家好.. 感谢您的快速回复。我认为我的问题不够清楚。我的 source/files.txt 包含 10 个文件名,这些文件名需要作为值分配给变量 $src 我正在使用这个脚本 link

标签: php variables text-files filenames


【解决方案1】:

好的,您想从 .txt 文件的每一行中获取文件名。

<?php
    $myFile = "files.txt";
    $lines = file($myFile);
    foreach($lines as $line){
    $file = basename($line);
    echo $file; 
    }
?>

回答您的旧问题变体

您可以使用basename() 函数。手册说,“给定一个包含文件或目录路径的字符串,此函数将返回尾随名称组件”。

现在,您说“我想从 source/files.txt 获取文件名到 $src”,因此假设您正在寻找文件名,即 black.png。这可以使用前面提到的 basename() 函数来实现。

<?php
$src='source/images/black.png';
$file = basename($src);
echo $file;
?>

输出

黑色.png

http://ideone.com/p2b4sr

【讨论】:

  • 谢谢。我需要一点不同的是,变量 $src 必须从包含文件名列表的 source/files.txt 中获取值。
  • 您明确提到“现在我想从 source/files.txt 获取文件名到 $src 我该怎么做?”。由此,我们暗示你想从你的 $src 变量中获取文件名,在这里你有一个答案。
  • 是的,很抱歉……我在办公桌上匆匆输入了那个……需要替换为“现在我想从 source/files.txt 中获取 $src 的值怎么能我这样做.?”。有什么想法吗?”
  • 我们需要查看更多代码和数据,.txt 文件包含哪些内容,并附有示例,因此请考虑编辑您的问题 Starr。
  • 谢谢.. 我已经创建了数组。它工作正常。
猜你喜欢
  • 1970-01-01
  • 2014-10-31
  • 2022-01-20
  • 2018-05-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-13
  • 1970-01-01
相关资源
最近更新 更多