I have a URL, which contains XML of products.
What I'm looking to do, is, if possible, parse the contents and then import the details as products into Magento.
Is this possible and If so, what would be the steps I need to do to carry this out?
Thanks
EDIT:
import_products.php
require_once('app/Mage.php');
class import_products extends Mage_Core_Model_Abstract
{
public static function url_contents($url)
{
$crl = curl_init();
$timeout = 5;
curl_setopt ($crl, CURLOPT_URL,$url);
curl_setopt ($crl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($crl, CURLOPT_CONNECTTIMEOUT, $timeout);
$ret = curl_exec($crl);
curl_close($crl);
return $ret;
}
}
import.php
require_once('import_products.php');
$app = Mage::app('default');
$product = Mage::getSingleton('catalog/product');
$objDOM = new DOMDocument();
$objDOM->load("http://www.example.com/products.xml");
$note = $objDOM->getElementsByTagName("car");
// for each note tag, parse the document and get values for
// tasks and details tag.
foreach( $note as $value )
{
$car_ids = $value->getElementsByTagName("Car_ID");
$car_id = $car_ids->item(0)->nodeValue;
$makes = $value->getElementsByTagName("Make");
$make = $makes->item(0)->nodeValue;
$models = $value->getElementsByTagName("Model");
$model = $models->item(0)->nodeValue;
$descriptions = $value->getElementsByTagName("Description");
$description = $descriptions->item(0)->nodeValue;
$short_descriptions = $value->getElementsByTagName("Specification");
$short_description = $short_descriptions->item(0)->nodeValue;
$prices = $value->getElementsByTagName("Price");
$price = $prices->item(0)->nodeValue;
$simple = 'simple';
$product->setAttributeSetId(4);
$product->setSku($task);
$product->setName($detail);
$product->setTypeId($simple);
$product->setPrice($price);
$product->setValue($price);
$product->setDescription($description);
$product->setShortDescription($short_description);
$product->setWeight(100);
$product->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_NOT_VISIBLE);
$product->setStatus(Mage_Catalog_Model_Product_Status::STATUS_ENABLED);
$product->setTaxClassId(2);
$product->setStockData(array(
'is_in_stock' => 1,
'qty' => 99999
));
try {
$product->save();
echo "Saved";
}
catch (Exception $ex) {
echo "<pre>".$ex."</pre>";
}
//echo "$car_id :: $make :: $model :: $description :: $short_description :: $price <br /><br />";
}
you could get the parameter in Magento and use simple xml to turn the string into xml
$xmlstr = self::XML_DECLARATION . urldecode($this->getRequest()->getParam('paramName');
try {
$xml = simplexml_load_string($xmlstr);
}
catch(Exception $ex) {
echo "Unable to process xml file because of the following error<br /><br /> $ex";
exit;
}
if it is a file you are trying to get you can setup a php file with the following code in it to get the contents of the url
function get_url_contents($url){
$crl = curl_init();
$timeout = 5;
curl_setopt ($crl, CURLOPT_URL,$url);
curl_setopt ($crl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($crl, CURLOPT_CONNECTTIMEOUT, $timeout);
$ret = curl_exec($crl);
curl_close($crl);
return $ret;
}
You can use that function and then where in the above we had
$xmlstr = self::XML_DECLARATION . urldecode($this->getRequest()->getParam('paramName');
You should be able to do this
$xmlstr = self::XML_DECLARATION . get_url_contents('http://urlhere.com/xml');
Then you could use simple xml and assign the nodes to a products array, where you could have a collection of products and then loop through those and programmatically create the products in Magento with something like this, obviously change the values that might be hard coded for whatever you might need.
$product = Mage::getSingleton('catalog/product');
// Build the product
$product->setSku($productData['sku']);
$product->setAttributeSetId(26);
$product->setTypeId('simple');
$product->setName($productData['description']);
$product->setCategoryIds(array(162));
$product->setWebsiteIDs(array(1));
$product->setDescription($productData['description']);
$product->setShortDescription($productData['description']);
$product->setPrice($productData['price']); # Set some price
$product->setWeight(4.0000);
$product->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_NOT_VISIBLE);
$product->setStatus(Mage_Catalog_Model_Product_Status::STATUS_ENABLED);
$product->setData('is_salable', '1');
$product->setTaxClassId(2); # My default tax class
$product->setStockData(array(
'is_in_stock' => 1,
'qty' => 99999
));
try {
$product->save();
}
catch (Exception $ex) {
//Handle the error
}
Related
First I want to say that this text was translated by Google Translate ( Excuses !).
How do I send data from an external server for my Magento store?
I looked hard for it today and found nothing basically want another system sends a notification to my Magento store and change the status of my order , I have not found a way to receiving external data in my store.
If you already have a related question I apologize.
Edit
This is my external file that sends the data:
$fields = '';
foreach($data as $key => $value) {
$fields .= $key . '=' . $value . '&';
}
rtrim($fields, '&');
$post = curl_init();
curl_setopt($post, CURLOPT_URL, $url);
curl_setopt($post, CURLOPT_POST, 1);
curl_setopt($post, CURLOPT_POSTFIELDS, $fields);
curl_setopt($post, CURLOPT_RETURNTRANSFER, 1);
var_dump($fields);
try {
$result = curl_exec($post);
$info = curl_getinfo($post);
echo curl_getinfo($post, CURLINFO_HTTP_CODE);
echo "<br>";
echo var_dump($info);
} catch (\Exception $e) {
$result = $e->getMessage();
echo $e;
}
}
$data = array(
"name" => "c.bavota",
"website" => "http://bavotasan.com",
"twitterID" => "bavotasan"
);
post_to_url("http://localhost/magento/safe/teste/mostra/", $data);
?>
This is my controller in Magento:
<?php
class Name_MyModule_TesteController extends Mage_Core_Controller_Front_Action{
public function mostraAction(){
$teste = $this->getRequest()->getPost('name');
echo 'Olá mundo';
echo '<br>Teste: '.isset($teste);
}
}
ps: I'm testing with locally with WAMP
Currently we have a Magento ver. 1.8.1.0 with installed PayPal Website Payments Standard option enabled. However when I want to do an online refund it doesn't show an 'Refund' button but only 'Offline refund'.
Is it actually possible to create an online refund with PayPal Standard?
Impossible with Paypal standard, you must overload the paypal standard model to implement the refund method, or you can install a module.
As luigifab said, that functionality isn't part of the Paypal module - I've implemented a small add-on for it that can be seen here:
https://gist.github.com/bubach/ed86611c634b401e5d66392cf32c2f6e
The most important part being this class:
<?php
class Namespace_Modulename_Model_Paypal extends Mage_Paypal_Model_Standard
{
protected $_canRefund = true;
protected $_canRefundInvoicePartial = true;
protected $_canVoid = true;
/**
* https://developer.paypal.com/webapps/developer/docs/classic/api/merchant/RefundTransaction_API_Operation_NVP/
*/
public function tryRefund(Varien_Object $payment, $amount)
{
$transactionId = $payment->getLastTransId();
if ($transactionId) {
$order = $payment->getOrder();
$storeId = $order->getStoreId();
$refundType = "Partial";
$invoiceFee = $payment->getMethodInstance()->getInfoInstance()->getAdditionalInformation('invoice_fee');
$remaining = $order->getTotalInvoiced() - ($order->getTotalOfflineRefunded() + $order->getTotalOnlineRefunded()) - $invoiceFee;
if (abs($remaining - $amount) < 0.00001) {
$refundType = "Full";
}
$currencyCode = $order->getBaseCurrencyCode();
$invoiceId = $order->getIncrementId();
$params = array(
"METHOD" => "RefundTransaction",
"VERSION" => "72.0",
"TRANSACTIONID" => $transactionId,
"INVOICEID" => $invoiceId,
"REFUNDTYPE" => $refundType,
"AMT" => $amount,
"CURRENCYCODE" => $currencyCode,
"USER" => Mage::getStoreConfig('paypal/wpp/api_username', $storeId),
"PWD" => Mage::getStoreConfig('paypal/wpp/api_password', $storeId),
"SIGNATURE" => Mage::getStoreConfig('paypal/wpp/api_signature', $storeId)
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api-3t.paypal.com/nvp");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
$response = curl_exec($ch);
if (curl_errno($ch)) {
curl_close($ch);
throw new Mage_Core_Exception('Impossible to issue a refund transaction because of cURL error.');
} else {
curl_close($ch);
$responseArray = array();
parse_str($response, $responseArray); // Break the NVP string to an array
if ($responseArray['ACK'] == "Success") {
return array(0, "Paypal refunded successfully");
} else {
return array(-1, "Paypal refund failed!");
}
}
} else {
Mage::throwException(Mage::helper('paypal')->__('Impossible to issue a refund transaction because the capture transaction does not exist.'));
}
}
}
I used the following function to get google search images
function get_images($query){
$url = 'http://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=';
$url .= urlencode($query);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($curl);
curl_close($curl);
//decoding request
$result = json_decode($data, true);
return $result;
}
It works good when I output all results using print_r()
$images = get_images("porsche");
print_r($images);
But when I want to get a specific value using foreach()
foreach ($images->responseData->results as $result) {
echo $result->url;
}
I got an error:
Notice: Trying to get property of non-object
How can I get any specific value separetly using foreach()?
Try this :
<?php
function get_images($query){
$url = 'http://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=';
$url .= urlencode($query);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($curl);
curl_close($curl);
//decoding request
$result = json_decode($data, true);
return $result;
}
$images = get_images("porsche");
//print_r($images);
foreach ($images['responseData']['results'] as $result) {
echo $result['url']. "<br>";
}
?>
Output
http://upload.wikimedia.org/wikipedia/commons/e/e7/2012_NAIAS_Red_Porsche_991_convertible_(world_premiere).jpg
http://www.inautonews.com/wp-content/uploads/2012/05/porsche-911-club-coupe-1.jpg
http://o.aolcdn.com/hss/storage/adam/6e58b30fb96bf0d28d10fa6d290682e7/porsche-exclusive-911t-cab.jpg
http://media.caranddriver.com/images/media/510773/porsche-960-updated-inline-photo-514518-s-original.jpg
i have use below code to add product in magento but not success ,anyone know how to do?
code here
code txt file
require_once $mageFilename;
Mage::setIsDeveloperMode(true);
umask(0);
Mage::app();
Mage::app()->setCurrentStore(Mage::getModel('core/store')->load(Mage_Core_Model_App::ADMIN_STORE_ID));
$product = new Mage_Catalog_Model_Product();
$product->setSku('A123');
$product->setAttributeSetId(4);
$product->setTypeId('simple');
$product->setName('Some cool product name');
$product->setCategoryIds(array(19));
$product->setWebsiteIDs(array(1));
$product->setDescription('Full description here');
$product->setShortDescription('Short description here');
$product->setPrice(39.99);
$product->setWeight(4.0000);
$product->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH);
$product->setStatus(1);
$product->setTaxClassId(0);
$product->setStockData(array(
'is_in_stock' => 1,
'qty' => 99999
));
$product->setCreatedAt(strtotime('now'));
try {
$product->save();
}
catch (Exception $ex) {
}
?>
i hope it may bemage.php path issue.Try put proper of mage file path
Suppose,My Magento path is /home/abc/www/www/ in server.
and my script file location location in /home/abc/www/www/try/dot/myscript.php
If you try to include mage.php from myscript.php then
$mageFilename = '/home/abc/www/www/app/Mage.php'
or
$mageFilename = '../../app/Mage.php'
i have run your script with modify mage.php file location call in script.it is works
I've been using this code to add/update products on Magento.
<?php
include_once("app/Mage.php");
Mage::app();
umask(0);
Mage::app()->setCurrentStore(Mage::getModel('core/store')->load(Mage_Core_Model_App::ADMIN_STORE_ID));
$counter = 0;
I have this function to get (or create) a product by SKU:
function GetProduct($sku)
{
global $counter;
echo $sku;
$p = Mage::getModel('catalog/product');
$productId = $p -> getIdBySku($sku);
if($productId)
{
echo "!";
$p -> load( $productId );
}
else
{
$p->setTypeId('simple');
$p->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH);
$p->setStatus(1);
$p->setTaxClassId(7);
$p->setWebsiteIDs(array(1));
$p->setStoreIDs(array(1));
$p->setAttributeSetId(4);
$p->setSku($sku);
}
echo "...";
$counter++;
echo " ".$counter;
return $p;
}
Here's the function to save the product:
function SaveProduct($p)
{
try
{
if (is_array($errors = $p->validate()))
{
$strErrors = array();
foreach($errors as $code=>$error)
{
$strErrors[] = ($error === true)? Mage::helper('catalog')->__('Attribute "%s" is invalid.', $code) : $error;
echo $strErrors[0];
}
$this->_fault('data_invalid', implode("\n", $strErrors));
}
$p->save();
echo "\n";
}
catch (Mage_Core_Exception $e)
{
$this->_fault('data_invalid', $e->getMessage());
}
}
And finally I'm calling like this:
$product = GetProduct('sku1');
$product->setData('thumbnail_label', 'sku1');
SaveProduct($product);
unset($product);
$product = GetProduct('sku2');
$product->setData('url_path', 'plastic-hat.html');
SaveProduct($product);
unset($product);
$product = GetProduct('sku3');
$product->setData('thumbnail_label', 'sku3');
SaveProduct($product);
unset($product);
$product = GetProduct('sku4');
$product->setData('thumbnail_label', 'sku4');
SaveProduct($product);
unset($product);
$product = GetProduct('sku5');
$product->setData('thumbnail_label', 'sku5');
SaveProduct($product);
unset($product);
I run this code from the command-line as there is a memory leak running it this way. You can only get so many products updated before it blows the memory and you have to edit and re-run the code to keep going, but it works and it's relatively fast.
You should be able to slot your code in quite nicely.
I am using Facebook PHP SDK 3.1.1
This page is supposed to collect value from header and later use it for uploading images.
Problem: $_SESSION['file'] becomes null after user logs in to Facebook.
<?php
require 'facebook.php';
include('connect.php');
$facebook = new Facebook(array('appId' => "XXXXXX",'secret' => "XXXXX","cookie" => true,'fileUpload' => true));
session_start();
$user_id = $facebook->getUser();
if(isset($_REQUEST["src"]))
{
echo "<center><img src='loader.gif'/></center>";
echo "<center><div id='msg'>Exporting Image..</div></center>";
$_SESSION['file'] = $_REQUEST["src"];
$_SESSION['club'] = $_REQUEST["club"];
}
$code = $_REQUEST["code"];
if(empty($code))
{
$_SESSION['state'] = md5(uniqid(rand(), TRUE));
$dialog_url = "http://www.facebook.com/dialog/oauth?client_id=". $app_id . "&redirect_uri=" . urlencode($my_url) . "&state=". $_SESSION['state'];
echo("<script> top.location.href='" . $dialog_url . "'</script>");
exit();
}
$token_url = "https://graph.facebook.com/oauth/access_token?". "client_id=" . $app_id . "&redirect_uri=" . urlencode($my_url). "&client_secret=" . $app_secret . "&scope=user_photos,email,read_stream,publish_stream&code=".$code;
function url_get_contents ($Url) {
if (!function_exists('curl_init')){
die('CURL is not installed!');
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $Url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
curl_close($ch);
return $output;
}
$response = url_get_contents($token_url);
$params = null;
parse_str($response, $params);
$graph_url = "https://graph.facebook.com/me?access_token=". $params['access_token'];
$user = json_decode(url_get_contents('https://graph.facebook.com/me/albums?access_token='.$params['access_token']),true);
foreach($user as $key=>$value)
{
foreach($user[$key] as $key1=>$value1)
{
if($value1['name'] == "Photos")
{
$album_uid = $value1['id'];
}
}
}
if(!isset($album_uid))
{
echo 'Create an album';
$album_details = array(
'message'=> 'Uploaded via XXX',
'name'=> 'Photos'
);
$create_album = $facebook->api('/me/albums', 'post', $album_details);
$album_uid = $create_album['id'];
}
$photo_details = array('message'=>$_SESSION["club"]);
try{
$file = NULL;
$file="../Photos/".$_SESSION['file'].".jpeg";
echo '<script>document.getElementById("msg").innerHTML = "Uploading Image"</script>';
$photo_details['image'] = '#' . realpath($file);
$upload_photo = $facebook->api('/'.$album_uid.'/photos', 'post', $photo_details);
}catch(Exception $e){
echo "<script type='text/javascript'>top.location.href = 'http://www.facebook.com/PAGE_URL/';</script>";
exit();
}
$_SESSION['file'] is null
Am I doing it right ? or something is wrong with my web hosting ?
The problem is that your app is running inside of an IFRAME and the session cookies are not being preserved. Please see here:
Facebook Iframe App with multiple pages in Safari Session Variables not persisting