Search code examples
phpcastingphp-5.3

How do I properly typecast PHP variables with SimpleXMLElement?


I'm pulling data from an XML feed and manipulating it using the awesome SimpleXMLElement. However, when I pull a node that is strictly numbers, I can't echo that node's values.

After investigating, a comment here http://www.php.net/manual/en/class.simplexmlelement.php#100162 mentioned that PHP sometimes incorrectly typecasts these nodes. However, when I typecast the variable as a string, it still won't appear. Code below:

$wAresult = $wunderAXmlObject->xpath("//moon_phase");

$current_sunrise = (string) $wAresult->sunrise[0]->hour[0]
    . ':' . (string) $wAresult->sunrise[0]->minute[0];

Can some explain how to properly typecast so this will work properly? Thanks!

Edit: I did a var_dump() to help diagnose the problem. Strangely, those numbers appear to be set as strings. At this point I'm unsure if I am accessing elements properly, although I will continue to update this question.

array(1) {
    [0]=> object(SimpleXMLElement)#336 (5) {
        ["percentIlluminated"]=> string(2) "74"
        ["ageOfMoon"]=> string(2) "20"
        ["current_time"]=> object(SimpleXMLElement)#331 (2) {
            ["hour"]=> string(2) "20"
            ["minute"]=> string(2) "34"
        }
        ["sunset"]=> object(SimpleXMLElement)#337 (2) {
            ["hour"]=> string(2) "16"
            ["minute"]=> string(2) "39"
        }
        ["sunrise"]=> object(SimpleXMLElement)#338 (2) {
            ["hour"]=> string(1) "8"
            ["minute"]=> string(2) "03"
        }
    }
}

Solution

  • Most likely it should be $wAresult[0]->sunrise->hour