[英]PHP - Read text file and output contents as links won't work
I have a text file in the same folder as the script I'm trying to run. 我的文本文件与我要运行的脚本位于同一文件夹中。 It has several URL links each on a new line like so: 它有几个URL链接,每个链接都位于新行中,如下所示:
hxxp://www.example.com/example1/a.doc
hxxp://www.example.com/example2/b.xls
hxxp://www.example.com/example3/c.ppt
I'm trying to link these files but it only lists the last file in the list. 我正在尝试链接这些文件,但它仅列出了列表中的最后一个文件。
Here is my code: 这是我的代码:
<?php
$getLinks = file_get_contents($_SERVER['DOCUMENT_ROOT'] . '/links.txt');
$files = explode("\n", $getLinks);
foreach ($files as $file) {
if (substr($file, 0, 23) == 'hxxp://www.example.com/') {
$ext = pathinfo(strtolower($file));
$linkFile = basename(rawurldecode($file));
if ($ext['extension'] == 'doc') {
echo '<a href="' . $file . '"><img src="images/word.png" /> ' . $linkFile . '</a><br />';
} elseif ($ext['extension'] == 'xls') {
echo '<a href="' . $file . '"><img src="images/excel.png" /> ' . $linkFile . '</a><br />';
} elseif ($ext['extension'] == 'ppt') {
echo '<a href="' . $file . '"><img src="images/powerpoint.png" /> ' . $linkFile . '</a><br />';
}
}
}
?>
*note: I've tried using the file function as well with the same results. *注意:我也尝试过使用文件功能,但结果相同。
You can improve this code in many ways: 您可以通过多种方式改进此代码:
file
instead of file_get_contents
to have the lines put into an array automatically 使用file
而不是file_get_contents
将行自动放入数组中 strpos
instead of substr
-- more efficient 使用strpos
而不是substr
更有效 strrpos
to get the file extension -- faster and foolproof, as know exactly how it behaves 使用strrpos
来获取文件扩展名-更快,更简单,确切地知道它的行为 rawurlencode
instead of rawurldecode
because you are creating urls, not reading them 您应该使用rawurlencode
而不是rawurldecode
因为您创建的是网址,而不是读取网址 if
conditionals for the extensions should be replaced by an array lookup 扩展的if
条件应替换为数组查找 Making all these changes, we have: 进行所有这些更改,我们有:
$lines = file($_SERVER['DOCUMENT_ROOT'] . '/links.txt');
$extensions = array(
'doc' => 'word.png',
'xls' => 'excel.png',
'ppt' => 'powerpoint.png',
);
foreach ($lines as $file) {
if (strpos($file, 'hxxp://www.example.com/') !== 0) {
continue;
}
$ext = strtolower(substr($file, strrpos($file, '.') + 1));
if (empty($extensions[$ext])) {
continue;
}
printf('<a href="%s"><img src="images/%s" /> %s</a><br />',
$file, $extensions[$ext], rawurlencode(basename($file)));
}
$getLinks = file_get_contents($_SERVER['DOCUMENT_ROOT'] . '/links.txt');
$files = explode("\r\n", $getLinks);
I'm assuming you're on windows, the same as me. 我假设你和我一样在Windows上。
\\n
isn't the whole windows new line character Use \\r\\n
\\n
不是整个Windows换行符使用\\r\\n
When I replaced \\n with \\r\\n it worked as expected 当我将\\ n替换为\\ r \\ n时,它按预期工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.