SimpleXMLElement - HTTP status code?

462 views Asked by At

I'm working with the PHP Steam Condenser library, to grab some Steam details about a user. I've successfully implemented this and everything is working. However I started to notice an error being thrown every so often, from Steam Condenser.

What's happening is, when I call the SteamId class with a param, the library generates a URL and makes a request to it, using SimpleXMLElement (as can be seen here). Now most of the time, the URL returns XML and so my application works fine, however every so often Steam throws back a 503 Service Unavailable back, causing it to fail.

try {
        return @new SimpleXMLElement($url, 0, true);
    } catch (Exception $e) {
        $errorMessage = "XML could not be parsed: " . $e->getMessage();
        if ((float) phpversion() < 5.3) {
            throw new SteamCondenserException($errorMessage, 0);
        } else {
            throw new SteamCondenserException($errorMessage, 0, $e);
        }
    }

In my cause, the PHP version is correct, so it throws the bottom custom Exception:

SteamCondenserException
XML could not be parsed: String could not be parsed as XML
/home/user/public_html/acme/vendor/koraktor/steam-condenser/lib/steam/community/XMLData.php (Line 38)

Although this is technically the correct exception, it isn't very meaningful since the request was just "Unavailable" and therefore couldn't gather the XML.

How would I go about editing this code to first check what the status code of the request is, if it's a 302 or 200 (since it redirects), then proceed to check the XML, otherwise if it's a 503, respond with a more genuine error (The Steam Community API is currently down) - or something.

I've Google'd my ass off, but can't see anything. Ideally I'd like it all to be done in the same request, since Steam can be a little slow sometimes.

Cheers

1

There are 1 answers

7
Halcyon On BEST ANSWER

Don't use SimpleXMLElement to also do the HTTP request.

Use curl (because it's fast) to fetch the XML plain-text and SimpleXML to parse it.

That way you can separate service availability from transmission errors (or XML errors).