How get the product SKU in XML magento 1.9
-
16-12-2020 - |
Question
I want to create a product XML file like this:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<root>
<stocks>
<product>
<sku>883503536128</sku>
<eansku>883503536128</eansku>
<stock>982</stock>
</product>
</stocks>
</root>
How can this be done?
Solution
Based on: https://gist.github.com/Nolwennig/b67bbbcba359c04fe77df9393dc3907a
You can put this script in root directory, aside of app/
<?php
if(php_sapi_name() != 'cli')
{
die('only via cli');
}
require 'app/Mage.php';
umask(0);
error_reporting(E_ALL);
ini_set('display_errors', 'on');
Mage::app('admin');
$resource = Mage::getSingleton('core/resource');
/* @var $resource Mage_Core_Model_Resource */
$conn = $resource->getConnection('core_write');
/* @var $conn Varien_Db_Adapter_Interface */
$dir = Mage::getBaseDir().DS.'export';
if(!is_dir($dir))
{
mkdir($dir, 0755, true);
}
$newFile = $dir . DS . 'product.xml';
$tmpFile = $newFile . '.tmp';
$fp = fopen($tmpFile, 'w');
fwrite($fp, '<?xml version="1.0" encoding="UTF-8" standalone="no"?>'."\n");
fwrite($fp, '<root>'."\n");
fwrite($fp, '<stocks>'."\n");
$collection = Mage::getModel('catalog/product')->getCollection();
foreach($collection as $_product)
{
fwrite($fp, '<product>'."\n");
fwrite($fp, ' <sku><![CDATA['.$_product->getSku().']]></sku>'."\n");
fwrite($fp, ' <eansku><![CDATA['.$_product->getEansku().']]></eansku>'."\n");
fwrite($fp, ' <stock>'.$_product->getQty().'</stock>'."\n");
fwrite($fp, '</product>'."\n");
}
fwrite($fp, '</stocks>'."\n");
fwrite($fp, '</root>'."\n");
fclose($fp);
@unlink($newFile);
rename($tmpFile, $newFile);
I write this quickly, without test and just a quick final checking. Test and review before run that.
OTHER TIPS
Please follow these steps:
Get the list of products you want to include in the XML file. For example, if you want to include all enabled products, then:
$products = Mage::getModel('catalog/product')->getCollection()
->addAttributeToSelect('*')
->addAttributeToFilter(
'status',
array('eq' => Mage_Catalog_Model_Product_Status::STATUS_ENABLED)
);
Then loop through all products and put the required attributes in the XML file.
Note: To know how to create XML file programmatically, please check https://stackoverflow.com/questions/486757/how-to-generate-xml-file-dynamically-using-php
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange