PHP&amp; HTML <a href=""> leaving extra space?

时间:2017-01-03 20:32:32

标签: php html

I have the following PHP code

$links = fopen("./links/links.txt", "r");
if ($links) {
    while (($line = fgets($links)) !== false) {
        $linkData = explode(" ", $line);
        /// The line below is the problematic one
        echo "<a href='".$linkData[0]."' class='links-item'>".$linkData[1]."</a><br>";
    }

    fclose($links);
} else {
    die('Error opening file, try refreshing.');
}

You can see I've seperated the line I'm having issues with. I have the following file links.txt

http://example.com Example

http://example2.com Example2

Basically this will add the URL in the text file to an anchor tag, and it'll add the text next to it, as the anchor display text. It works, but for some reason, every anchor tag ends with a space, except the last one. Anyone know why this is and how I can fix it?

3 个答案:

答案 0 :(得分:4)

fgets()返回的字符串包括分隔行的换行符。这将是$linkData[1]的结尾,所以你写的是

<a href='http://example.com' class='links-item'>Example
</a><br>

输出。

您可以改为使用fgetcsv(),将空格指定为字段分隔符。这将为您爆炸线并自动忽略换行符。

while (($linkData = fgetcsv($links, 0, " ")) !== false) {
    echo "<a href='".$linkData[0]."' class='links-item'>".$linkData[1]."</a><br>";
}

答案 1 :(得分:1)

fgets()在字符串中捕获换行符和单词字符。使用trim功能删除不需要的空格:

echo "<a href='".trim($linkData[0])."' class='links-item'>".trim($linkData[1])."</a><br>";

或者,正如@Barmar所说,你可以使用fgetcsv function

答案 2 :(得分:1)

使用

var_dump($linkData);

查看fgets()返回的内容。也许有意想不到的人物。

考虑使用更高级的文件格式,例如,您可以使用csv格式并使用http://php.net/manual/en/function.fgetcsv.php从文件中检索结果。

相关问题