rick
rick

Reputation: 33

creating xml file

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";
            }

Upvotes: 3

Views: 888

Answers (2)

Michael Berkowski
Michael Berkowski

Reputation: 270599

If id is to be an attribute, then you need to use the DOMElement::setAttribute() method. I think this will work - according to the documentation, if an attribute doesn't already exist it will be created.

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

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

Upvotes: 0

Asaph
Asaph

Reputation: 162761

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");
?>

Upvotes: 2

Related Questions