SimpleXML IF condition


SimpleXML IF condition

我有一个XML文档,它将返回URL或错误代码。如果它返回错误代码,我想将页面重定向到错误图像。我可以让SimpleXML返回URL,但如果返回错误,我不确定如何编写条件。如果有人有什么建议,那就太好了!这就是我现在拥有的:

<?php
error_reporting(0);
$url = 'http://radiocast.co/art/api1/key=KeyHere&album=' . htmlspecialchars($_GET["album"]) . '&artist=' . htmlspecialchars($_GET["artist"]) . '';
$xml = simplexml_load_file($url);
$img = $xml->xpath('//image[@size="large"]');
$large = (string)$img[0];
header("Location:".urldecode($large));
?>

如果找不到XML文档,则返回以下内容:

<?xml version="1.0" encoding="utf-8"?>
<lookup status="failed">
<error code="3">Art not found</error></lookup>

检查XML中的错误节点,如果找到它,然后处理各种错误如何?如果你没有找到它,你可以继续你的正常逻辑。

if (isset($xml->error)) {
    switch ($xml->error['code']) {
        case '3':
            // not found stuff here
            break;
        // other error codes here
    }
} else {
    // success logic here
    $img = $xml->xpath('//image[@size="large"]');
    $large = (string) $img[0];
    header("Location: " . urldecode($large));
}