tdc
tdc

Reputation: 5464

Can't edit/save DOM XML Element Attribute using DomDocument

I have an XML file like below. I have to use the DOMDocument, so no extra classes allowed. (note I have simplified it, the real file has many entries in both saleItems and catalogItems):

<?xml version="1.0"?>
<catalog>
    <saleItems count="3">

        <item name="Xbox 360 Wired Controller" price="19" stock="50" salePrice="12" onSale="yes">
            <image>Xbox360Controller.jpg</image>
            <description>A wired controller for an Xbox 360 Game Console. Comes in either white or black.</description>
        </item>

    </saleItems>

    <catalogItems count="12">
        <item name="Dell Alienware Laptop 15 inch" price="2500" stock="200" salePrice="0" onSale="no">
            <image>alienwareLaptop.jpg</image>
            <description>sample description here</description>
        </item>
    </catalogItems>
</catalog>

I need to do the following:

1) find the node to update based on the name="" attribute (ex: the only data I have to find the appropriate item is the item name)

2) when it is found, I need to edit the quantity attribute of just that item (subtract 1)

3) when the quantity has been updated, I need the XML file to be saved back to the server.

I'm at whits ends with this, I'm having a hard time getting the $domDocument to cooperate.. This is what I have so far, but it does not seem to work properly at all. I can get the stock and substract it, but my changes aren't being saved to the file.

foreach( $GLOBALS['catalogItems'] as $item ){
    if( $item->getAttribute('name') == $itemName ){
        // we have a match
        $oldStock = $item->getAttribute("stock");
        $item->setAttribute("stock", $oldStock + $modifier);

        $dom->save('xml/catalog.xml');
    }
}

any help much appreciated!

Upvotes: 1

Views: 702

Answers (1)

Levi Morrison
Levi Morrison

Reputation: 19552

Solved via PHP chat: https://chat.stackoverflow.com/transcript/message/7402294#7402294

The problem was that his selector for $GLOBALS['catalogItems'] included DOMText items, which would fail when calling $item->getAttribute('name'). The solution is to make sure $item is actually an item node and then to do the other checks if it an item.

Upvotes: 1

Related Questions