-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathadd_product.php
55 lines (46 loc) · 1.96 KB
/
add_product.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
<?php
$errors = array(); // array to hold validation errors
$data = array(); // array to pass back data
// validate the variables ======================================================
if (empty($_POST['product_name']))
$errors['product_name'] = 'Product Name is required.';
if (empty($_POST['quantity']))
$errors['quantity'] = 'Quantity is required.';
if (empty($_POST['price']))
$errors['price'] = 'Price is required.';
// return a response ===========================================================
if ( ! empty($errors)) {
// if there are items in our errors array, return those errors
$data['success'] = false;
$data['errors'] = $errors;
} else {
$xmldoc = new DOMDocument();
$xmldoc->encoding = 'utf-8';
$xmldoc->xmlVersion = '1.0';
$xmldoc->formatOutput = true;
$xml_file_name = 'products_list.xml';
if($xml = @file_get_contents($xml_file_name)){
$xmldoc->loadXML($xml);
$root = $xmldoc->getElementsByTagName('Products')->item(0);
} else {
$root = $xmldoc->createElement('Products');
}
$movie_node = $xmldoc->createElement('product');
$child_node_title = $xmldoc->createElement('Name', cleanData($_POST['product_name']));
$movie_node->appendChild($child_node_title);
$child_node_year = $xmldoc->createElement('QuantityInStock', cleanData($_POST['quantity']));
$movie_node->appendChild($child_node_year);
$child_node_genre = $xmldoc->createElement('PricePerItem', cleanData($_POST['price']));
$movie_node->appendChild($child_node_genre);
$child_node_genre = $xmldoc->createElement('CreatedAt', date('Y-m-d H:i:s'));
$movie_node->appendChild($child_node_genre);
$root->appendChild($movie_node);
$xmldoc->appendChild($root);
$xmldoc->save($xml_file_name);
$data['success'] = true;
$data['message'] = 'Product has been added!';
}
echo json_encode($data);
function cleanData($string) {
return preg_replace('/[^A-Za-z0-9\-\.\s]/', '', $string);
}