user3812146
user3812146

Reputation: 1

Update XML using PHP

$xml = simplexml_load_file('xml/item.xml');

$xml->item[$_POST['number']]->itemname = $_POST['name'];

$xml->item[$_POST['number']]->description = $_POST['description'];

$xml->item[$_POST['number']]->price = $_POST['price'];

file_put_contents('xml/item.xml', $xml->asXML());

I want update my XML based on index number coming from form number. But in this code i got "PHP Warning: Creating default object from empty value" error. Please advice on this.

Upvotes: 0

Views: 111

Answers (1)

someOne
someOne

Reputation: 1675

It seems you haven't checked against the existence of the $_POST['number'] and the warning arises as the value is not set, the general good practice is to always check against variables, so add the following to the beginning of your code:

if(isset($_POST['number'])) {
...

(consider checking against other variables and function-returns in final production as good programming practice :)


P.S: The actual cause of the warning is the out of range problem (PHP will add a node after the warning generation). In the following code I just checked for the existence of the node index, and in the case of non-existence, just added a new node (in this simple implementation, the index of the new node is not necessarily equal to $_POST['number'], you may change the behavior to suit your needs):

if(isset($_POST['number'])) {
    $xml = simplexml_load_file('xml/item.xml');

    if(isset($xml->item[$_POST['number']]))
        $node = $xml->item[$_POST['number']];
    else
        $node = $xml->addChild('item');

    $node->itemname = $_POST['name'];
    $node->description = $_POST['description'];
    $node->price = $_POST['price'];

    file_put_contents('xml/item.xml', $xml->asXML());
}


Disclaimer: The error message of the same issue in PHP 5.4.0 - 5.6.8 is as the following (I use v5.5.8):

Warning: main(): Cannot add element item number 5 when only 0 such elements exist in ...

The warning message in the original post reads:

Warning: Creating default object from empty value in ...

Which is exactly the same message as the warning generated when you try the $xml->item[null] (in my PHP version).

Upvotes: 1

Related Questions