Search code examples
phpsimplexmlkml

PHP SimpleXMLElement - accessing values with in an element


I am reading a KML file in php using SimpleXMLElement class. The last elements in the tree look like the example below (var_dump of php object say $element):

object(SimpleXMLElement)#2 (2) {
  ["@attributes"]=>
  array(1) {
    ["name"]=>
    string(10) "featurecla"
  }
  [0]=>
  string(15) "Admin-0 country"
}

How do I access "Admin-0 country" value in php?

I have tried both $element->children() and $element->attributes() and only be able to access "featurecla" only.


Solution

  • I have found the solution

    Turns out I was not examining the KML file properly, and just looking at php var_dump outputs to understand the data structure. The KML file data looked like below:

    <Folder><name>ne_50m_admin_0_countries</name>
      <Placemark>
        <name>Zimbabwe</name>
        <Style><LineStyle><color>ff0000ff</color></LineStyle><PolyStyle><fill>0</fill></PolyStyle></Style>
        <ExtendedData><SchemaData schemaUrl="#ne_50m_admin_0_countries">
            <SimpleData name="featurecla">Admin-0 country</SimpleData>
    

    In the PHP code, I was using the code below to access the SimpleData:

    foreach($xmlContent->Document->Folder->children() as $Placemark){
            print_r("<h1>".(string)$Placemark->name."</h1>");
            foreach ($Placemark->ExtendedData->SchemaData->SimpleData as $element){
                var_dump($element); //output shown above
                var_dump($element->children());
                var_dump($element->attributes());
                            }
        }
    

    After looking at the raw kml file, I was able to access the required information:

    foreach($xmlContent->Document->Folder->children() as $Placemark){
            print_r("<h1>".(string)$Placemark->name."</h1>");
    
            foreach ($Placemark->ExtendedData->SchemaData->SimpleData as $element){
    
                echo $element->attributes()."=>";
                echo $element."<br>";           
                //output featurecla=>Admin-0 country
            }
        }