Extracting Values from SimpleXMLElement Objects
When working with SimpleXMLElement in PHP, a common stumbling block occurs when you expect primitive values like floats or strings but receive object instances instead. This specific behavior often confuses developers because the API appears inconsistent: accessing $xml->code[0]->lat returns a float (e.g., 52.25), yet accessing $xml->code[0]->postalcode might return an object depending on how the XML is parsed or if nested structures are involved.
The root of this issue lies in how SimpleXMLElement handles data types internally. It attempts to cast child nodes to their native PHP equivalents (integers, floats, strings) when they represent simple scalar values. However, if a node contains whitespace-only content, is empty, or if the XML parser encounters specific structural quirks, it may return the element as its full object representation rather than casting it immediately.
In your specific example with the GeoNames API, the structure shows nested SimpleXMLElement objects for administrative divisions (adminCode1, adminName1, etc.). While your code successfully extracts $xml->code[0]->lat, accessing properties that might be empty or structured differently can trigger the object behavior you observed. To reliably extract values regardless of whether the internal state is a scalar or an object, you must explicitly cast the result to a string or use the asText() method.
Explicit Casting for Reliability
The most robust approach is to treat every access as potentially returning an object and force a type conversion immediately. This prevents "object vs scalar" errors later in your application logic.
Instead of relying on implicit casting, use string() casting or the dedicated asText() method:
$cityCode[] = array(
'city' => $city[$i],
// Force string conversion to handle both scalar and object cases
'lat' => (string)($xml->code[0]->lat),
'lng' => (string)($xml->code[0]->lng),
// If accessing nested empty objects, this prevents object references
'adminName1' => (string)($xml->code[0]->adminName1 ?? '')
);
Using the (string) cast is generally preferred for numeric coordinates like latitude and longitude. It ensures you are working with a string representation that can be easily passed to other functions, stored in arrays, or concatenated without triggering unexpected object method calls. The asText() method achieves the same result but is more verbose; stick to the cast operator for cleaner code unless you specifically need the behavior of asText() regarding null handling.
Handling Empty Nodes and Nulls
A frequent pitfall when parsing XML via SimpleXMLElement is accessing nodes that do not exist or contain only whitespace. In your dump, adminCode1 shows as an empty object. If you try to cast an empty object to a string without checking first, you might get unexpected results or warnings depending on the PHP version and specific XML content.
Always check for null or empty states before casting if the data structure is optional:
$lat = (string)($xml->code[0]->lat ?? '');
$lng = (string)($xml->code[0]->lng ?? '');
$adminName1 = (string)($xml->code[0]->adminName1); // May be empty string or object cast to ''
// If the node is missing entirely, simplexml_load_file might return false or a specific structure
if ($xml === false || !isset($xml->code[0])) {
throw new Exception("No postal code data found for city: " . $city[$i]);
}
The Trade-off of SimpleXML
While SimpleXMLElement is convenient for quick parsing, it lacks the type safety and structural validation of dedicated XML parsers like DOMDocument or DOMXPath. If you are building a high-traffic application where data integrity is critical, consider switching to DOM-based parsing for large datasets or complex schemas. However, for simple API calls like the GeoNames example, the overhead of switching parsers often outweighs the benefits.
The key takeaway is that SimpleXMLElement is dynamic and context-dependent. By explicitly casting your retrieved values to strings using (string), you insulate your application from the internal state of the XML object. This pattern ensures that whether the API returns a number, a string, or an empty node, your code handles it consistently as a string value ready for use.
