Search code examples
phpsimplexml

How could I create 2 same XML-Tags by using SimpleXML in PHP?


I have wrote this PHP code to create a XML data:

$xml = new SimpleXMLElement("<?xml version=\"1.0\" encoding=\"utf-8\"?><Products></Products>");
$xml->addChild("Product");
$xml->Product->addChild("Name", "P1");
$xml->Product->addChild("Price", "10");
$xml->addChild("Product");
$xml->Product->addChild("Name", "P2");
$xml->Product->addChild("Price", "20");

The XML what I got is:

<?xml version="1.0" encoding="utf-8"?>
<Products>
  <Product>
    <Name>P1</Name>
    <Price>10</Price>
    <Name>P2</Name>
    <Price>20</Price>
  </Product>
  <Product/>
</Products>

But what I want is:

<?xml version="1.0" encoding="utf-8"?>
<Products>
  <Product>
    <Name>P1</Name>
    <Price>10</Price>
  </Product>
  <Product>
    <Name>P2</Name>
    <Price>20</Price>
  </Product>
</Products>

How could I get the right XML? Thanks!


Solution

  • A simple change to this should do it...

    $xml = new SimpleXMLElement("<?xml version=\"1.0\" encoding=\"utf-8\"?><Products></Products>");
    $product = $xml->addChild("Product");
    $product->addChild("Name", "P1");
    $product->addChild("Price", "10");
    $product = $xml->addChild("Product");
    $product->addChild("Name", "P2");
    $product->addChild("Price", "20");
    

    The problem is you were re-selecting the first element from the XML root when adding your sub elements.