douzhe3516 2016-10-01 18:28
浏览 41
已采纳

当文本文件为空时隐藏回声输出

I have a blog/vlog where I also share my listening habits from Spotify live. I use a little snippet called Snip (available on Github) that fetches my Spotify stream, creates text files for my data (like track, artist, album and trackID)

Now I wanted to add a link on my webpage to the actual track I am playing using the variable $i for trackID

I've come up with this code thanks to some googling and tips/trix pages:

<?php
$myfile = fopen("Snip_TrackId.txt", "r") or die("Die!"); 
echo "<a href='https://open.spotify.com/track/";
echo fread($myfile,filesize("Snip_TrackId.txt"));
echo "'target='_blank'><img width='18px' height='18px' title='Open with Spotify' src='np_spotify.png'><a/> <- Listen";
fclose($myfile);
?>

This works just fine, but when I close down Spotify or pause, the text files empty themselves and my info box turns blank AND THAT'S THE WAY IT SHOULD BE :). B ut...... With my code above, the link, image and text "<- Listen" is still visible and I've been trying to figure out how I can fix this but I'm stuck. (The link is also not really working as it only points to the part without the trackID)

So now I turn to you. Can you help me with a working solution for this? If not, I will probably just keep things as they are.

  • 写回答

2条回答 默认 最新

  • douwen4178 2016-10-01 18:36
    关注

    Before writing a link check file for emptiness for example:

    $file = "Snip_TrackId.txt";
    if (0 < filesize($file)) {
        $myfile = fopen("Snip_TrackId.txt", "r") or die("Die!"); 
        echo "<a href='https://open.spotify.com/track/";
        echo fread($myfile,filesize("Snip_TrackId.txt"));
        echo "'target='_blank'><img width='18px' height='18px' title='Open with   Spotify' src='np_spotify.png'><a/> <- Listen";
        fclose($myfile);
    }
    

    Or if file contains spaces - check read data:

    $myfile = fopen("Snip_TrackId.txt", "r") or die("Die!"); 
    $data = trim(fread($myfile,filesize("Snip_TrackId.txt")));
    if ($data) {
        echo "<a href='https://open.spotify.com/track/";
        echo $data;
        echo "'target='_blank'><img width='18px' height='18px' title='Open with   Spotify' src='np_spotify.png'><a/> <- Listen";
    }
    fclose($myfile);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 BV260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序