I've been messing around with simplexml_load_file() function which returns SimpleXMLElement and for learning purposes, I tried the weather.gov restful services to bring some data and see how it works.
So basically this is what I did:
$xml = simplexml_load_file("http://www.weather.gov/forecasts/xml/sample_products/browser_interface/ndfdXMLclient.php?whichClient=NDFDgen&lat=38.99&lon=-77.01&listLatLon=&lat1=&lon1=&lat2=&lon2=&resolutionSub=&listLat1=&listLon1=&listLat2=&listLon2=&resolutionList=&endPoint1Lat=&endPoint1Lon=&endPoint2Lat=&endPoint2Lon=&listEndPoint1Lat=&listEndPoint1Lon=&listEndPoint2Lat=&listEndPoint2Lon=&zipCodeList=&listZipCodeList=¢erPointLat=¢erPointLon=&distanceLat=&distanceLon=&resolutionSquare=&listCenterPointLat=&listCenterPointLon=&listDistanceLat=&listDistanceLon=&listResolutionSquare=&citiesLevel=&listCitiesLevel=§or=&gmlListLatLon=&featureType=&requestedTime=&startTime=&endTime=&compType=&propertyName=&product=time-series&begin=2004-01-01T00%3A00%3A00&end=2015-06-10T00%3A00%3A00&maxt=maxt&Submit=Submit");
var_dump($xml);
The link belong to weather.gov and a rest service.
And now my question comes:
When I dumped the variable something took my attention and I couldn't find a way to describe it to myself.
Here is some piece of the dumped variable:
object(SimpleXMLElement)[1]
public '@attributes' =>
array
'version' => string '1.0' (length=3)
public 'head' =>
object(SimpleXMLElement)[2]
public 'product' =>
object(SimpleXMLElement)[4]
public '@attributes' =>
array
...
When I saw public '@attributes' => array I thought I could reach the variable typing $xml->attributes['version'] but I was wrong since I learned this was the correct way $xml['version'] and I started wonder how it is possible since $xml became array here but this code also works fine after running the first code $xml->head->product->title which returns the value of the title element defined under head > product.
It looks like an indexers like in C#. Basically this is a valid code in c# below:
public int this[int index] // Indexer declaration
{
// get and set accessors
}
But I couldn't think of a way which provides the same functionality in PHP classes.
Can somebody tell me how the '@attributes' is called in PHP, an indexer? And how to achieve this functionality in PHP.
Objects of classes that inherit from ArrayObject and/or implement ArrayAccess (which ArrayObject itself implements) can be accessed with indexers. Although SimpleXMLElement itself doesn't implement either one (it's probably an internal implementation), you can achieve the same functionality in your own classes using them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With