PHP - 读取文本文件和输出内容作为链接将无法正常工作

时间:2011-03-21 18:05:50

标签: php

我在与我正在尝试运行的脚本相同的文件夹中有一个文本文件。它在新行上有几个URL链接,如下所示:

hxxp://www.example.com/example1/a.doc
hxxp://www.example.com/example2/b.xls
hxxp://www.example.com/example3/c.ppt

我正在尝试链接这些文件,但它只列出列表中的最后一个文件。

这是我的代码:

<?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" />&nbsp;' . $linkFile . '</a><br />';
            } elseif ($ext['extension'] == 'xls') {
                echo '<a href="' . $file . '"><img src="images/excel.png" />&nbsp;' . $linkFile . '</a><br />';
            } elseif ($ext['extension'] == 'ppt') {
                echo '<a href="' . $file . '"><img src="images/powerpoint.png" />&nbsp;' . $linkFile . '</a><br />';
            }
        }
    }

?>

*注意:我也尝试过使用文件功能,结果相同。

2 个答案:

答案 0 :(得分:1)

您可以通过多种方式改进此代码:

  1. 使用file代替file_get_contents将行自动放入数组
  2. 使用strpos代替substr - 更高效
  3. 使用strrpos获取文件扩展名 - 更快更准确,因为确切知道它的行为方式
  4. 您应该使用rawurlencode代替rawurldecode,因为您正在创建网址,而不是正在阅读
  5. 扩展的if条件应由数组查找替换
  6. 进行所有这些更改后,我们有:

    $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" />&nbsp;%s</a><br />',
               $file, $extensions[$ext], rawurlencode(basename($file)));
    }
    

答案 1 :(得分:0)

$getLinks = file_get_contents($_SERVER['DOCUMENT_ROOT'] . '/links.txt');
$files = explode("\r\n", $getLinks);

我假设你在窗户上,和我一样。

\n不是整个Windows新行字符使用\r\n

当我用\ r \ n替换\ n时,它按预期工作

相关问题