Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transforming an XSD template to an XML instance in PHP

Tags:

php

xml

xsd

I have an XSD file(s), and I need to generate a valid sample XML from that XSD file. For example, given the following XSD:

<?xml version="1.0" encoding="utf-8"?>
<xs:schema elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="Address">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="Recipient" type="xs:string" default="John Doe" />
        <xs:element name="Street" type="xs:string" />
        <xs:element name="age" type="xs:integer"/>
        <xs:element name="dateborn" type="xs:date"/>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

Generate the following XML:

<xml>
    <Address>
        <Recipient>John Doe</Recipient>
        <Street></Street>
        <age>43</age>
        <dateborn>1970-03-27</dateborn>
    </Address>
</xml>

I've searched for a solution in PHP that is capable of performing this, but only to come across two possible solutions but with no success.

  1. Using SDO_DAS_XML . However, this depends on tha availability of php_sdo.dll, to which there doesn't seem be a version that actually works on Windows.

  2. Second try was to look at github.com/moyarada/XSD-to-PHP or forums.devshed.com/php-development-5/xml-schema-binding-to-php-code-jaxb-equivalent-199799.html However, these are targeted at parsing XSD and transforming to PHP classes and don't seem to be generic enoguh to transform any XSD to a simple clean XML (like above).

Any ideas or solutions are much appreciated :)

Thanks!

like image 464
Zohar.Babin Avatar asked Feb 02 '11 18:02

Zohar.Babin


1 Answers

I've found that the only reasonable way to perform this task is to treat your XSD as any XML, use DOMDocument to parse it and build your specialized XML instances from it.

  • This method assumes that your XSD will always have the same structure, only different names to fields, and that you're interested in a very simple form of XML instance, meaning the nodes and nothing more.
  • The benefit of that method is in flexibility, simply edit the foreach loop to modify your special structure.
//Build the template from the schema:
$schema = new DOMDocument();
$schema->loadXML($schemaXSDFile); //that is a String holding your XSD file contents
$fieldsList = $schema->getElementsByTagName('element'); //get all elements 
$metadataTemplate = '';
foreach ($fieldsList as $element) {
    //add any special if statements here and modify the below to include any attributes needed
    $key = $element->getAttribute('name');
    $metadataTemplate .= '<' . $key . '>' . '</' . $key . '>';
}

//Manipulate the template adding your fields values:
$metadataXml = simplexml_load_string($metadataTemplate);
$metadataXml->fieldName = 'value';
like image 87
Zohar.Babin Avatar answered Oct 06 '22 23:10

Zohar.Babin