0
$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.

CodeWithCoffee
  • 1,896
  • 2
  • 14
  • 36
  • Based on [this](http://stackoverflow.com/a/8900730/4499267) one of the properties you're trying to access is not defined – Phate01 May 12 '15 at 11:41
  • Could you please add the output of `var_dump($_POST);` in when the problem occurs. – someOne May 12 '15 at 11:58
  • Would you show us your xml file. – splash58 May 12 '15 at 14:04
  • Hi user, do a simple debug: `var_dump($xml);` on line 2. Then edit your question with the results you get. – michi May 12 '15 at 15:10
  • array(6) { ["optionselect"]=> string(6) "update" ["number"]=> string(1) "5" ["name"]=> string(5) "Colon" ["description"]=> string(11) "Paris Colon" ["price"]=> string(4) "450$" ["submit"]=> string(6) "Submit" } – user3812146 May 12 '15 at 15:39

1 Answers1

1

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).

someOne
  • 1,975
  • 2
  • 14
  • 20