Xml file creation

I am creating an xml file as shown below, can anyone help how to get this with php?

xml file:

<products>
<product id="123" />
</products>

Php file:

I am using the following code but not getting the result as above

$xml = new DomDocument('1.0', 'utf-8');
$xml->formatOutput = true;
$products= $xml->createElement('products');
$product = $xml->createElement('product');
$id = $xml->createElement('id');
$xml->appendChild($products);
$products->appendChild($product);
$product->appendChild($id);
$id->nodeValue = 123; 
$xml->save("data.xml");

xml data extraction:

         $xml = new DomDocument();
         $xmlFile = "data.xml";
         $xml= DOMDocument::load($xmlFile);
         $product = $xml->getElementsByTagName("product");             
         foreach($product as $node) 
            { 
        $address = $node->getElementsByAttributeName("address");
        $address = $address->item(0)->nodeValue;
          echo"$address";
            }
+3
source share
2 answers

You do not get the desired results, because you add idas a tag, and not as an attribute. I reworked your code a bit and made idan attribute. I checked the code below and it gives the desired result.

<?php
$xml = new DomDocument('1.0', 'utf-8');
$xml->formatOutput = true;
$products= $xml->createElement('products');
$product = $xml->createElement('product');
$xml->appendChild($products);
$products->appendChild($product);
$product->appendChild(new DomAttr('id', '123'));
$xml->save("data.xml");
?>
+2
source

If it idshould be an attribute, you need to use a method DOMElement::setAttribute(). I think this will work - according to the documentation , if the attribute does not exist yet, it will be created.

$product->setAttribute("id", "123");

Then loas $product->appendChild( $id );

0
source

All Articles