簡體   English   中英

使用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花費了一段時間,但現在修復了,我評論了有助於修復它的地方。 感謝大家的幫助。

如果調用失敗(遠程服務器不可用),並且XML中是否存在某種錯誤消息,則應檢查simplexml_load_string是否返回false。 如果存在,則應跳過信息並顯示錯誤。 我無法告訴您它們如何在XML中隱藏,但是很可能有標簽或類似的東西。

編輯:剛在PHP文檔中看到,simplexml_load_string需要格式正確的XML字符串。 也許您應該檢查您是否真的有一個格式正確的XML。 最好的辦法是查看文檔並按照需要的方式更改代碼。

如果您擔心示例中有時會出現PHP“ Notice”或“ Warning”消息,則可以在相關的函數調用(在本例中為“ simplexml_load_string”)前面加上“ @”符號,以禁止顯示任何內容。這樣的消息。

例如:

$xml = @simplexml_load_string($data);

有關更多信息, 請參見PHP的錯誤控制手冊

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM