Magento – Reading Data from Magento Table and converting it to XML

magento-1.8PHPxml

I'm able to read the the product name and description using the following queries on the magento database table using PHP.

SELECT value FROM mg_catalog_product_entity_varchar WHERE attribute_id = 71 AND entity_id = $entityid

SELECT value FROM mg_catalog_product_entity_text WHERE attribute_id = 72 AND entity_id = $entityid

The data extracts successfully and it displays content when I just echo. But when i Convert the extracted data to xml im getting the error. If I do not provide the $entityid variable then the last record is extracted and successfully converts to xml. If i provide a static value in place of $entityid i'm getting that particular value, in XML but when i provide the variable name it throws an error. PFB the error image

enter image description here

XML code that creates the node. This code is placed within a while loop

        $xml_entityid = $xml->createElement( "productid", $entityid );
        $xml_productname = $xml->createElement( "productname" , $productname);
        $xml_descrp = $xml->createElement( "description" , $descriptionn );

        $xml_product->appendChild( $xml_entityid );
        $xml_product->appendChild( $xml_productname );
        $xml_product->appendChild( $xml_descrp );

        $xml_products->appendChild( $xml_product );

Best Answer

here is a built in way to export a product as xml.

$product = Mage::getModel('catalog/product')->load($entityId);
$xml = $product->toXml();

This will generate an xml with all the product attributes.
If you want to have only the name and description, do this:

 $xml = $product->toXml(array('name', 'description'));   

This will generate something like :

<item>
    <name>Name here</name>
    <description>Description here</description>
</item>

If you want to change the tag item into something else, call it like this:

 $xml = $product->toXml(array('name', 'description'), 'product');   

If you want the xml header <?xml version="1.0" encoding="UTF-8"?> call it like this:

 $xml = $product->toXml(array('name', 'description'), 'product', true);

and because the description can contain special chars it may be a good idea to add <![CDATA[]]> around the values. For that supply a 4th parameter true:

 $xml = $product->toXml(array('name', 'description'), 'product', true, true);

[EDIT]

The method toXml I used above is defined in Varien_Object class. If you are trying to achieve this outside Magento, you can add that class to your project and use it to generate xmls.
After retrieving the data from the db, just create an instance of Varien_Object and set the name and description.

$obj = new Varien_Object();
$obj->setName(your name from the db);
$obj->setDescription(your description from the db);

$xml = $obj->toXml(array('name', 'description'), 'product', true, true);

//$xmlObj = simplexml_load_string($xml); //if you need it as an object
Related Topic