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 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛