note 52583 modified in ref.simplexml by danbrown

From: Date: Mon, 18 May 2009 01:27:44 +0000
Subject: note 52583 modified in ref.simplexml by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-155539@lists.php.net to get a copy of this message
Hi, If you want to access an element that has a dash in its name, (as is common with the XML documents provided by the Library of Congress, as well as the NWS) you will need to handle it a little bit differently. You can either use XPATH, which works fine, but will return an array of results every time, even if there is a single result. eg. <?php $xml->xpath('/data/time-layout/start-valid-time'); ?> You can also choose just to encapsulate the element names containing a dash: <?php $xml->data->{'time-layout'}->{'start-valid-time'} ?> -- On a only partially related note, dealing with SimpleXML is one of the only times I have employed casting with PHP. While iterating (foreach) through the valid times, echo'ing the element worked great (it merely echo'ed the apropriate time), assigning it to another variable resulted in a SimpleXML object containing the time to be assigned, rather than just the time itself. This was resolved by casting the time to a string: <?php foreach($xml->data->{'time-layout'}->{'start-valid-time'} AS $time) { $weatherDates[] = (string) $time; } ?> --was-- Hi, If you want to access an element that has a dash in its name, (as is common with the XML documents provided by the Library of Congress, as well as the NWS) you will need to handle it a little bit differently. You can either use XPATH, which works fine, but will return an array of results every time, even if there is a single result. eg. $xml->xpath('/data/time-layout/start-valid-time'} You can also choose just to encapsulate the element names containing a dash: $xml->data->{'time-layout'}->{'start-valid-time'} -- On a only partially related note, dealing with SimpleXML is one of the only times I have employed casting with PHP. While iterating (foreach) through the valid times, echo'ing the element worked great (it merely echo'ed the apropriate time), assigning it to another variable resulted in a SimpleXML object containing the time to be assigned, rather than just the time itself. This was resolved by casting the time to a string: foreach($xml->data->{'time-layout'}->{'start-valid-time'} AS $time) { $weatherDates[] = (string) $time; } http://php.net/manual/en/ref.simplexml.php

« previous php.notes (#155539) next »