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.
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.
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!
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.
//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';
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