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";
}
You are not getting the results you want because you’re adding
idas a tag rather than an attribute. I just refactored your code a little and madeidan attribute. I tested the code below and it produces your desired result.