Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

creating xml file

Tags:

php

xml

I am creating xml file as below, can anybody help how to get that using php?

xml file:

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

Php file:

i am using following code but not getting 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");

retrieving xml data:

         $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";
            }
like image 249
rick Avatar asked Jul 11 '26 21:07

rick


1 Answers

You are not getting the results you want because you're adding id as a tag rather than an attribute. I just refactored your code a little and made id an attribute. I tested the code below and it produces your 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");
?>
like image 103
Asaph Avatar answered Jul 14 '26 11:07

Asaph



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!