如何不用PHP脚本创建新行

With the script below, I create links from a text file you, but when I create files, I can line added at the beginning and one at the end of lines, no way to prevent that from happening? The first line of file.txt and Live1 and the last line of https://www.example.com/example/playlist.m3u8 but when I do the transformation in link.txt file, the first and last lines are empty, I would avoid creating empty rows, It's possible? where am I wrong?

This is file.txt

Live1 
https://www.example.com/example/playlist.m3u8
Live2 
https://www.example.com/example/playlist.m3u8
Live3 
https://www.example.com/example/playlist.m3u8
Live4 
https://www.example.com/example/playlist.m3u8
Live5 
https://www.example.com/example/playlist.m3u8

This is the script php

<?php
$file = "file.txt";
$fr = fopen($file, 'r');
$i = $x = 0;
$links = array();
while (!feof($fr)) {
    $riga = trim(fgets($fr));
    if (!empty($riga)) {
        if ($i % 2 == 0) {
            $links[$x]['name'] = $riga;
        } else {
            $links[$x]['link'] = $riga;
            $x++;
        }
        $i++;
    }
}
fclose($fr);

$output = "";
foreach ($links as $link) {
    $output .= "<a href='" . $link['link'] . "' target='blank'>" . $link['name'] . "
 " ;
$file = "link.txt";
$codice = "
{$output}
";
$fo = fopen($file, "w");
chmod($file, 0755);
fwrite($fo, $codice);
fclose($fo);
}

This is the result link.txt

<a href='https://www.example.com/example/playlist.m3u8'>Live1
<a href='https://www.example.com/example/playlist.m3u8'>Live2
<a href='https://www.example.com/example/playlist.m3u8'>Live3
<a href='https://www.example.com/example/playlist.m3u8'>Live4
<a href='https://www.example.com/example/playlist.m3u8'>Live5

You're explicitly creating new lines:

$codice = "
{$output}
";

If you don't want them, get rid of them:

$codice = "{$output}";

(Or just use the $output variable directly, since $codice isn't actually doing anything.)