Axel
Axel

Reputation: 62

Dynamically editing XML in PHP

I'm trying to read and write to an XML file that is always different.

What I want to do is define CSS properties that can be changed for each class/id in my css (which is done by php).

So an element could look like this:

<element id="header">
    <position>left</position>
    <background>#fff</background>
    <color>#000</color>
    <border>2px dotted #GGG</border>
</element>

But the inner nodes could change (any css property).

I want to read this and then make a form in which I can edit the properties (managed to do this).

Now I need to save the XML. I can't submit the complete form at once, because of PHP (Can't submit forms you don't know the form-element names). I'm trying to do it with Ajax and save each node when edited in the form. (onChange)

So I know the "id" tag of the element and the node name. But I couldn't find a way to directly access the node and edit it with DOMDocument or SimpleXML.

I've been told to try XPath, but I couldn't use XPath to edit.

How could I attempt to do this?

Upvotes: 0

Views: 409

Answers (1)

DaveRandom
DaveRandom

Reputation: 88687

$xml = <<<XML
<rootNode>
    <element id="header">
        <position>left</position>
        <background>#fff</background>
        <color>#000</color>
        <border>2px dotted #GGG</border>
    </element>
</rootNode>
XML;

// Create a DOM document from the XML string
$dom = new DOMDocument('1.0');
$dom->loadXML($xml);

// Create an XPath object for this document
$xpath = new DOMXPath($dom);

// Set the id attribute to be an ID so we can use getElementById()
// I'm assuming it's likely you will want to make more than one change at once
// If not, you might as well just XPath for the specific element you are modifying
foreach ($xpath->query('//*[@id]') as $element) {
    $element->setIdAttribute('id', TRUE);
}

// The ID of the element the CSS property belongs to
$id = 'header';

// The name of the CSS property being modified
$propName = 'position';

// The new value for the property
$newVal = 'right';

// Do the modification
$dom->getElementById($id)
    ->getElementsByTagName($propName)
    ->item(0)
    ->nodeValue = $newVal;

// Convert back to XML
$xml = $dom->saveXML();

See it working

Upvotes: 1

Related Questions