SimpleXML IF条件

时间:2012-02-14 21:35:35

标签: php xml simplexml

我有一个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>

1 个答案:

答案 0 :(得分:4)

如何检查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));
}