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