提问者:小点点

PHP/XML:如果图像不可用/在服务器上,请将图像src替换为另一个url


我的代码:

<?php

$Length = 25;
$rnd = substr(str_shuffle(md5(time())), 0, $Length);

$songs = [];

$channels = range(1,6);

// Download current songs (from 1 to 6)
foreach ($channels as $sid) {
    $song = file_get_contents(sprintf('http://95.154.254.129:17618/currentsong?sid=%s', $sid));
    list($artist, $title) = explode('-', $song, 2);
    $songs[] = [
        'rnd' => $rnd,
        'sid' => $sid,
        'image' => sprintf('http://95.154.254.129:17618/playingart?sid=%s&rnd=%s', $sid, $rnd),
        'song' => $song,
        'artist' => trim($artist),
        'title' => trim($title)
    ];
}
unset($song);
//print_r($songs);

// Write new xml file
$doc = new DOMDocument('1.0', 'UTF-8');
$doc->preserveWhiteSpace = false;
$doc->formatOutput = true;

$allChannels = $doc->createElement("allchannels");
$allChannels->setAttribute('count' , count($channels));
$doc->appendChild($allChannels);

$trackInfo = $doc->createElement("ilr_trackinfo");
$trackInfo->setAttribute('channel' , $song['sid']);

foreach ($songs as $song) {
    $trackInfo = $doc->createElement("ilr_trackinfo");
    $trackInfo->setAttribute('channel' , $song['sid']);
    $allChannels->appendChild($trackInfo);

    $artist = $doc->createElement("artist");
    $trackInfo->appendChild($artist);

    $artistCdata = $doc->createCDATASection($song['artist']);
    $artist->appendChild($artistCdata);

    $title = $doc->createElement("title");
    $trackInfo->appendChild($title);

    $titleCdata = $doc->createCDATASection($song['title']);
    $title->appendChild($titleCdata);

    $image = $doc->createElement("image");
    $image->setAttribute('src', $song['image']);
    $trackInfo->appendChild($image);
}

header("Content-type: text/xml");
echo $doc->saveXML();
?>

如果图像不可用,我需要将图像替换为:“http://www.reyfm.de/img/nocover.png”。

非常感谢帮助!:)

I need to add text... Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam.


共1个答案

匿名用户

这里有一个方法可以做到这一点。

foreach ($channels as $sid) {

    $song = file_get_contents(sprintf('http://95.154.254.129:17618/currentsong?sid=%s', $sid));
    list($artist, $title) = explode('-', $song, 2);

    $actualImageUrl = sprintf('http://95.154.254.129:17618/playingart?sid=%s&rnd=%s', $sid, $rnd);
    $placeholderImageUrl = "http://www.reyfm.de/img/nocover.png";
    $imageUrl = @getimagesize($actualImageUrl) ? $actualImageUrl : $placeholderImageUrl;

    $songs[] = [
        'rnd' => $rnd,
        'sid' => $sid,
        'image' => $imageUrl,
        'song' => $song,
        'artist' => trim($artist),
        'title' => trim($title)
    ];
}