你如何在使用PHP时跳过xml中的错误行?

时间:2013-12-15 00:02:08

标签: php xml parsing

我正在使用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 花了一段时间,但现在它修复了我评论了帮助修复它的地方。谢谢大家的帮助。

2 个答案:

答案 0 :(得分:0)

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

编辑:刚刚在PHP文档中看到,simplexml_load_string需要格式良好的XML字符串。也许你应该检查一下你是否真的有一个结构良好的XML。最好是查看docs并以您需要的方式更改代码。

答案 1 :(得分:0)

如果您关注有时似乎出现在您的示例中的PHP“Notice”或“Warning”消息,那么您可以使用“@”符号为相关函数调用(在本例中为“simplexml_load_string”)添加前缀压制任何此类消息。

例如:

$xml = @simplexml_load_string($data);

有关详细信息,请see PHP's manual for error control

相关问题