-1
<?php
 if (isset($_POST['submitProduct']))
 {
     $xml = new DomDocument("1.0", "UTF-8");
     $xml->load('./data/productDB.xml');

     $productName = $_POST['productName'];
     $productDescription = $_POST['productDescription'];
     $quantity = $_POST['quantity'];
     $stock = $_POST['stock'];
     $price = $_POST['price'];
     $size = $_POST['size'];
     $type = $_POST['type'];

     $rootTag = $xml->getElementsByTagName("root")->item(0);
     $infoTag = $xml->createElement("info");

     $productNameTag = $xml->createElement("product-name", $productName);
     $productDescriptionTag = $xml->createElement("product-description", $productDescription);
     $quantityTag = $xml->createElement("quantity", $quantity);
     $stockTag = $xml->createElement("stock", $stock);
     $priceTag = $xml->createElement("price", $price);


 
     $infoTag->append($productNameTag);
     $infoTag->append($productDescriptionTag);
     $infoTag->append($quantityTag);
     $infoTag->append($stockTag);
     $infoTag->append($priceTag);



     $rootTag->append($infoTag);
     $xml->save("productDB.xml");
 }
?>

Here, I have $size and $type which are arrays. However, if I use the following method to add these array to the xml:

$sizeTag = $xml->createElement("size", $size);

I get the following error: Warning: DOMDocument::createElement() expects parameter 2 to be string, array given

How do you write arrays to xml? Does PHP have a built in method?

jas305
  • 89
  • 1
  • 8
  • 1
    Does this answer your question? [How to convert array to SimpleXML](https://stackoverflow.com/questions/1397036/how-to-convert-array-to-simplexml) – SirPilan Aug 10 '20 at 19:11
  • I checked these out but they created a new SimpleXMLElement object and then printed the output out, I simply don't understand how will I integrate that code given my code. I cant see the link. – jas305 Aug 10 '20 at 19:16
  • 2
    That depends what you want the XML to look like - you could put a comma-separated list in one `` tag, you could have multiple `` tags with one value in each, you could have a `` tag with multiple `` tags inside it... Neither we nor PHP can make that decision for you, so there isn't really an answerable question here. – IMSoP Aug 10 '20 at 19:26
  • *I simply don't understand how will I integrate that code given my code* and yet you have accepted an answer which uses SimpleXML?! – Nigel Ren Aug 10 '20 at 19:29
  • it was an accident – jas305 Aug 10 '20 at 19:53

1 Answers1

0

Based on this.

if (isset($_POST['submitProduct'])) {
    // ...
    
    $data = [
        'productName' => $_POST['productName'],
        'productDescription' => $_POST['productDescription'],
        'quantity' => $_POST['quantity'],
        // ...
    ];

    $xml = new SimpleXMLElement('<root/>');
    array_walk_recursive($data, [$xml, 'addChild']);

    // ...
}
SirPilan
  • 4,649
  • 2
  • 13
  • 26