James May James May - 4 months ago 21
PHP Question

How to load schema, set properties and output a string without SDO?

After struggling with installing SDO on the server I found some information that SDO is not going to be further developed/supported.

How could this be done without SDO?

$das = SDO_DAS_XML::create("$someSchemaFile");
$doc = $das->createDocument();
$root = $doc->getRootDataObject();
$root->Data1 = 'data1';
$root->Data2 = 'data2';
$string = $das->saveString($doc);


Schema (pseudo)

<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:cc="http://cc/XMLSchema">
<xsd:element name="SomeName">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="Data1" type="xsd:string"/>
<xsd:element name="Data2" type="xsd:string"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>

Answer

XSD is XML itself, so you have several ways to go about it, like for instance DomDocument. But the easiest way would probably be SimpleXML, it's not quite as powerful but mostly you don't need that anyway.

Here's a little example:

$xml = <<<XML <?xml version="1.0" encoding="UTF-8"?> 
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
            xmlns:cc="http://cc/XMLSchema">
    <xsd:element name="SomeName">
        <xsd:complexType>
            <xsd:sequence>
                <xsd:element name="Data1" type="xsd:string"/>
                <xsd:element name="Data2" type="xsd:string"/>
            </xsd:sequence>
        </xsd:complexType>
    </xsd:element> </xsd:schema> 
XML;

$doc = simplexml_load_string($xml);

// get the first xsd:element node with a name-attribute of 'Data1' 
$element = $doc->xpath("//xsd:element[@name='Data1']")[0];

// change the name-attribute: 
$element->attributes()->name = 'SomeOtherName';

// or even add another attribute: 
$element->addAttribute('newAttribute', 'newAttributeValue');

// and spit it out as XML again:
echo $doc->asXML();

I hope this helps, since I'm not quite sure if that's what you had in mind. But as far as I understood your question you're just looking for an alternative / easy way to manipulate an XML file.