Reputation: 1
$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
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 :)
$_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());
}
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