Search code examples
xmlsimplexmlphp

How to escape colon when reading XML in PHP, simplexml


I have an XML file that I am trying to get variables off with PHP. The XML file looks like this:

<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:dcq="http://purl.org/dc/terms/" xmlns="http://www.skype.com/go/skypeweb">
<Status rdf:about="urn:skype:skype.com:skypeweb/1.1">

You can view the full XML file here: http://mystatus.skype.com/username.xml

I used the simplexml extension to convert the xml input into the PHP object $xml. When I attempt to navigate later in the file with:

$variable = $xml->rdf:RDF->Status->presence;

It gives me an error because of the colon in "rdf:RDF":

Parse error: syntax error, unexpected ':'

How can I either escape the colon, or navigate later in the file without changing the XML file?


Solution

  • Your initial code:

    $variable = $xml->rdf:RDF->Status->presence;
    

    does not work because it is creating a syntax error:

    Parse error: syntax error, unexpected ':' in /test.php on line 8

    The colon in the property name is not valid. PHP's common way to work with that are curly braces:

    $xml->{'rdf:RDF'}->Status->presence
    

    As you then found out you get the undefined property notice:

    Notice: Trying to get property of non-object in /test.php on line 8

    That is first-hand because such a property does not exists, var_dump shows that:

    var_dump($xml);
    
    class SimpleXMLElement#1 (1) {
      public $Status =>
      class SimpleXMLElement#2 (2) {
        public $statusCode =>
        string(1) "1"
        public $presence =>
        array(13) {
          [0] =>
          string(1) "1"
          ...
        }
      }
    }
    

    However, apart from that, even if there would be a children with a namespace prefixed element name, it would not work that way. This would just never work, so always such a property is not defined.

    However what the previous dump outlines is that there is the property you're looking for: $Status:

    $variable = $xml->Status->presence;
    

    So you were just looking in the wrong place. The var_dump($variable) is:

    class SimpleXMLElement#4 (13) {
        string(1) "1"
        string(7) "Offline"
        string(12) "Déconnecté"
        string(7) "Offline"
        string(15) "オフライン"
        string(6) "離線"
        string(6) "脱机"
        string(7) "Offline"
        string(7) "Offline"
        string(12) "Non in linea"
        string(12) "Desconectado"
        string(15) "Niepodłączony"
        string(7) "Offline"
    }