dongluo1853 2018-08-08 11:41
浏览 38
已采纳

在PHP中错误提取XML

I need to extract two data from an XML file. I am using this script:

Canzone in onda:

<?php
$estrazioneAPI = new SimpleXMLElement('http://api.radionomy.com/currentsong.cfm?radiouid=0523cc62-e00c-485e-8e65-aea2aa37702a&apikey=b3ec3722-a1e6-44af-9d95-cb97ade2f4dc&callmeback=yes&type=xml&cover=yes&previous=yes.xml', NULL, TRUE);
if(false === $estrazioneAPI)
{
  echo "test";
}
$canzoni = $estrazioneAPI->xpath("//tracks");
if(count($canzoni) > 0) {
    foreach($canzoni as $track) {
        $titolo = $track->track->title;
        $artista = $track->track->artists;
        if($titolo == '' AND $artista == ''){
        echo "Nessuna canzone in onda";
        }else if($titolo == '' AND $artista != ''){
                echo "$artista - Titolo non riconosciuto";
        }else if($titolo != '' AND $artista == ''){
                echo "Artista non riconosciuto - $titolo";
            }else{
                 echo $artista . " - " . $titolo;
            }
    }
}



?>
</marquee></i>

Going to the page where I put this script works correctly, the problem is that on another page I put this to update the data every 15 seconds:

<script>
$(document).observe('dom:loaded', function() {
  new Ajax.PeriodicalUpdater('canzoneInOnda', '../api_webbo/canzone_in_onda.php', { frequency: 15 });
});
</script>
<div id="canzoneInOnda"></div>

Everything is OK except that this writing comes out from time to time:

Fatal error: Uncaught exception 'Exception' with message 'String could not be parsed as XML

Then at the next update it returns to work normally... How could I solve?

  • 写回答

1条回答 默认 最新

  • dongqing7789 2018-08-08 13:53
    关注

    This because your returned XML is not valid. You should use try-catch and write log when an exception happens. And, we should not use SimpleXMLElement to get the url resource directly.

    <?php
    
    try {
        $url = 'http://api.radionomy.com/currentsong.cfm?radiouid=0523cc62-e00c-485e-8e65-aea2aa37702a&apikey=b3ec3722-a1e6-44af-9d95-cb97ade2f4dc&callmeback=yes&type=xml&cover=yes&previous=yes.xml';
        $ch = curl_init($url);
    
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
        $result = curl_exec($ch);
        curl_close($ch);
        $estrazioneAPI = new SimpleXMLElement($result);
        //Bla bla your code...
    
    
    } catch (Throwable $exception) {
        //Write log exception
        //echo $exception->getMessage();
        //var_dump($result);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀