Search code examples
phpxmlsimplexmldomdocument

How to read an Array of Element Names from XMLSchema XML File in PHP?


I wanted to get the list of schema elements from xml. For example

<xs:schema id="SPPOnlineXML" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
 <xs:element name="SPPOnlineXML" msdata:IsDataSet="true" msdata:MainDataTable="lev_settings" msdata:UseCurrentLocale="true">
  <xs:complexType>
    <xs:choice minOccurs="0" maxOccurs="unbounded">
      <xs:element name="lev_settings">
        <xs:complexType>
          <xs:sequence>
            <xs:element name="LEVID" type="xs:int" minOccurs="0" />
            <xs:element name="ATTHEADID" type="xs:int" minOccurs="0" />
            <xs:element name="MINDATETYPE" type="xs:unsignedByte" minOccurs="0" />
            <xs:element name="MINMONTH" type="xs:unsignedByte" minOccurs="0" />
          </xs:sequence>
        </xs:complexType>
      </xs:element>
    </xs:choice>
  </xs:complexType>
 </xs:element>
</xs:schema> 

from the above schema i wanted to create an array of elements "LEVID","ATTHEAD","MINDATETYPE","MINMONTH"


Solution

  • To obtain all xs:element name-attribute values as an array I suggest you pick SimpleXML and make use of xpath. Once you've got the XML in a string (or a file) it is really straight forward if you know the xpath expressions:

    # Obtain all element names incl. complexTypes:
    
    //xs:element/@name
    
    # Obtain all element names excl. complexTypes and those
    #  which contain anything incl. comments, text etc.:
    
    //xs:element[not(node())]/@name
    

    And per PHP code exmaple that looks like:

    $xml = simplexml_load_string($string);
    
    echo "Obtain all element names incl. complexTypes:\n";
    
    $elementNames = array_map('strval', $xml->xpath('//xs:element/@name'));
    print_r($elementNames);
    
    echo "\nObtain all element names excl. complexTypes and those
      which contain anything incl. comments, text etc.:\n";
    
    $elementNames = array_map('strval', $xml->xpath('//xs:element[not(node())]/@name'));
    print_r($elementNames);
    

    See the online Demo.