使用php时,如何跳过xml中的错误行


how do you skip errored lines in xml when using php?

我正在使用PHP和myanimelist API进行动画搜索。我遇到的问题是,每隔一段时间我就会搜索一些东西,结果会出现一堆XML错误。这很好,但它不会显示这里的信息是代码。

<?php
    error_reporting(E_ALL);
    ini_set('display_errors', 1);
    $search = $_GET['q'];
    $username = '';
    $password = '';
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "http://myanimelist.net/api/anime/search.xml?q=$search");
    curl_setopt($ch, CURLOPT_USERPWD,$username . ":" . $password);
    curl_setopt($ch, CURLOPT_HEADER, 'Magic Browser');
    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    //curl_setopt($ch, CURLOPT_TIMEOUT, 10 );
    $data = curl_exec($ch);
    $xml = simplexml_load_string($data);
    $image = $xml->entry[0]->image;
    $title =  $xml->entry[0]->title;
    $status = $xml->entry[0]->status;
    $synopsis = $xml->entry[0]->synopsis;
    echo "$image <br><br><b>Title</b>: $title  <br> <b>Status</b>: $status <br><b>Synopsis</b>: $synopsis";
    ?>

编辑固定

<?php
    ini_set('display_startup_errors', 1);
    error_reporting(E_ALL);
    ini_set('display_errors', 1);
    $search = $_GET['q'];
    $username = '';
    $password = '';
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "http://myanimelist.net/api/anime/search.xml?q=$search");
    curl_setopt($ch, CURLOPT_USERPWD,$username . ":" . $password);
    curl_setopt($ch, CURLOPT_HEADER, 'Magic Browser');
    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10 );
    $data = curl_exec($ch);
    //changed the encoding I don't know if it helped
    $data = str_replace('utf-8', 'iso-8859-1', $data);
    //replaced &mdash; so now it works
    $data = str_replace('&mdash;', ' ', $data);
    $xml = simplexml_load_string($data);
    $image = $xml->entry[0]->image;
    $title =  $xml->entry[0]->title;
    $status = $xml->entry[0]->status;
    $synopsis = $xml->entry[0]->synopsis;
    echo "$image <br><br><b>Title</b>: $title  <br> <b>Status</b>: $status <br><b>Synopsis</b>: $synopsis";
?>

我的意思的例子就在这里。http://vs3.yuribot.com/mal.php?q=naruto它花了一段时间,但现在已经修复了。我评论了帮助修复它的地方。谢谢大家的帮助。

如果调用失败(远程服务器不可用),您应该检查simplexml_load_string是否返回false,以及XML中是否存在某种错误消息。如果有,您应该跳过信息并显示错误。我不能告诉你它们是如何隐藏在XML中的,但很可能有一个标记或类似的东西。

编辑:刚才在PHP文档中看到simplexml_load_string需要一个格式良好的XML字符串。也许您应该检查一下您是否真的得到了一个格式良好的XML。最好的方法是查看文档并根据需要更改代码。

如果您关心示例中有时出现的PHP"Notice"或"Warning"消息,那么您可以在相关函数调用(在本例中为"simplexml_load_string")前面加上"@"符号来抑制任何此类消息。

例如:

$xml = @simplexml_load_string($data);

有关更多信息,请参阅PHP的错误控制手册。