Get XML Data into Magento via the Magento API

Get XML Data into Magento via the Magento API

NOTE: Before you get started, you need to make sure you have created an API user in Magento. Here is a good step-by-step tutorial for doing that.

I decided that because of the potentially massive amount of data in my dropshipper’s XML feed file, that I should save the file to my server before attempting to process any data. I set up a cron job to use CURL to fetch the file. First I created a file called ‘importproducts.php’ and added the following code:

importproducts.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
//my dropshipper's feed URL - replace with your dropshipper's feed
$myFeed = 'http://www.mydropshipperssite.com/feedurl.xml';
 
// specify the name of the file you want to save
$myFilename = 'product_feed.xml';
 
 
	if ($myFeed != '') {
	//  Initialize the cURL session
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $myFeed);
	//Create a new file
	$fp = fopen($myFilename, 'w');
	// Save to file
	curl_setopt($ch, CURLOPT_FILE, $fp);
	// Execute the cURL session
	curl_exec ($ch);
	//Close cURL session and file
	curl_close ($ch);
	fclose($fp);
 
	echo "Feed Imported Successfully!";
 
 
		//check the file size - if its 0 then my dropshipper didn't provide any updates, so don't let me know
		if (filesize($myFilename) > 0) {
 
			// send email to me when executed
			$to = "youremail@yourdomain.com";
			$subject = "Feed Imported";
			$body = "Hi,\n\nThe latest product data for YOURSITE has been downloaded on ";
			$body .= date('l jS \of F Y h:i:s A')."\n\n File Size: ".filesize($myFilename) . " bytes";
 
				if (mail($to, $subject, $body)) {
				  echo("<p>Message successfully sent!</p>");
					 } else {
				 echo("<p>Message delivery failed...</p>");
				}
 
		}
 
 
	}

Now that we have this script written, we need to process the data. Before that, let me show you an example of the xml data I am working with in the xml file we just saved with the import script. Here is sample xml:

product_feed.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?xml version="1.0" ?>
<products>
<product sku="15569" mfg_part_number="405970-1" upc="082324027055">
<inventory quantity="13"/>
<price your_price="143.18" list="159.99"/>
<description short="A product description"/>
</product>
 
<product sku="16128" mfg_part_number="406350-1" upc="082324029301">
<inventory quantity="0"/>
<price your_price="128.18" list="149.99"/>
<description short="Another product description"/>
</product>
</products>

Now we can talk about the next file, the one that takes the XML data and uses it to update products in Magento via the API. We’ll name this file ‘processupdates.php’.

processupdates.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
//include the Magento API file - replace with your server path to the file
require_once('/some/path/to/public_html/app/Mage.php');
 
// ***** Configuration ******
$myDomain = 'http://www.yourdomain.com';
$myAPILogin = 'username';
$myAPIKey = 'password';
 
//calculate the price markup - useful if you have a standard markup you apply
$myMarkUp = .30;
$defaultMarkup = .30;
 
// get my saved file name
$myFilename = 'product_feed.xml';
 
//load up local xml file for processing
$feed_xml = simplexml_load_file($myFilename);
 
// Begin SOAP Requests
$client = new SoapClient($myDomain.'/api/?wsdl');
$session = $client->login($myAPILogin, $myAPIKey);
 
$updatedProducts = "";
 
//some counters - counting loops this way lets me see and set where the count increments
$x = 0;
 
//some filter date to pass to the API - add more to filter your results further - see Magento API docs
$filterData = array('type'=>'simple');
 
//get all my database products into an array
$products = $client->call($session, 'catalog_product.list', array($filterData));
 
 
//loop through my product array
foreach ($products as $product) {
 
echo "Starting product loop...<br/><br/>";
 
 
//get my database product sku - for cleaner reference in the code
$mysku = $product['sku']
 
//search directly in the product sku attribute in the xml for my sku
$res = $feed_xml->xpath("//product[@sku='$mysku']");
 
 
// if we find one, lets process it
if(!empty($res)) {
 
	//matched - make updates
	echo "Matched: ".$mysku;
 
	//price updates
	if ($res[0]->price['list'] != '') {
		$newprice = $res[0]->price['your_price'] + (($res[0]->price['list'] - $res[0]->price['your_price'])*$myMarkUp);
	} else {
		$newprice = $res[0]->price['your_price'] + ($res[0]->price['your_price']*$defaultMarkup);
	}
 
	//build my array to pass to the magento API
	$fieldPriceData = array('cost'=>$res[0]->price['your_price']*1, 'price'=>$newprice, 'upc'=>$res[0]->product['upc']);
	//update magento with price data
	$client->call($session, 'catalog_product.update', array($product['sku'], $fieldPriceData));
 
	//qty and stock updates
	if (($res[0]->inventory['quantity']*1) != 0) {
		$fieldQtyData = array('qty'=>$res[0]->inventory['quantity']*1, 'is_in_stock'=>1);
		echo "In Stock<br/>";
	} else {
		$fieldQtyData = array('qty'=>$res[0]->inventory['quantity']*1, 'is_in_stock'=>0);
		echo "Out of Stock<br/>";
	}
 
	//update magento with quantity and stock data
	$client->call($session, 'product_stock.update', array($product['sku'], $fieldQtyData));
 
	//record the updated product for emailing later
	$updatedProducts .= "SKU: ".$mysku." - ".$res[0]->description['short']."\nPrice: ".$newprice."\nCost: ".$res[0]->price['your_price']."\nQty: ".$res[0]->inventory['quantity']."\n\n";
 
	//increment my counter
	$x = $x + 1; 
 
} else {
 
echo "no match<br/><br/>";
 
}
 
 
 
// send mail to me
$to = "you@yourdomain.com";
$subject = "Feed Processed";
$body = "Hi,\n\nThe latest data for ".$myDomain." has been processed on ".date('l jS \of F Y h:i:s A')."\n\n";
$body .= "Products Updated: ".$x."\n\n".$updatedProducts;
if (mail($to, $subject, $body)) {
  echo("<p>Message successfully sent!</p>");
	 } else {
 echo("<p>Message delivery failed...</p>");
}

Now all you need to do is set up the cron jobs to call your import file at one interval, and your process file at another interval. Note that this works for me because I have a limited number of database products. If you have thousands of products you might want to have your site updating products by category, for example. If anyone has any better ideas on how to do any of this, please let me know. I always like to learn new stuff!

Download Files: Magento API XML Import - 15.82 KB - 191 Downloads


Tags: , ,

Brian Wilhelm

I am a web entrepreneur, internet addict, e-commerce lover, and music fan. I currently work as Internet Marketing Director of a CPG company. In the past, I worked as a Director of E-Commerce Design for an Internet Retailer Hot 100 site, Design Manager, Web Developer, and Product Designer.

7 Comments Leave yours

  1. Sprice #

    Thanks this is just what I need. So far I’ve only done the import but it works perfectly.

    Keep up the good work!

  2. Daniel #

    I got some problems getting this to work… I can easily fetch the xml file from my supplier, but I cant seem to process the data. I have added a api / rule and put in the info, i also updated the file with all info, but when i try to call the file in the browser, i just get a blank screen.

    Can you help?

    I my xml file, the SKU it is not called product sku, but instead Product_Code,
    So is it right that I need to use following code :
    $res = $feed_xml->xpath(“Product_Code=’$mysku’”);

  3. Daniel #

    Keep getting an PHP Parse error: syntax error, unexpected T_VARIABLE in /var/www/domain.com/public_html/processupdates.php on line 62

    Also when i use the code
    $res = $feed_xml->xpath(“//product[@sku='$mysku']“);

    Any hints?

  4. Hi Daniel,

    W3C have a pretty good primer on Xpath here.

    I’d say its just a matter of using the right syntax to access the value you are looking for.

    In regards to the T_VARIABLE error, that usually happens when you have left out a closing curly bracket in your code.

  5. Paul #

    Hi There,

    Thank you for sharing this information, much appreciated.

    My feed is like this please can you help?

    19/01/2010 23:27:54
    2.0

    N0507
    example 1
    6
    In Stock

    Please can you tell me where to replace these files and how to setup the cron job.

    Many Thanks

    Paul

  6. Hi Paul,

    Unfortunately I can’t make much out of feed example you posted, so if you can repost the XML that would be helpful.

    As far as where to put the files, I think you can put them anywhere so long at the path to the mage.php file is correct on line 2 of the processupdates.php, but to be safe I would put them in the root folder of your magento install.

    In regards to Cron Jobs, you can read more about them here.

  7. Nathanial Meleo #

    yea nice Work

Leave a Reply