cancel
Showing results for 
Search instead for 
Did you mean: 

Issues getting products in the compare list from outside Magento

Issues getting products in the compare list from outside Magento

I am trying to get the products in the compare list from outside magento with a short PHP script, but I am having problems with it.

 

The intention is to gather the details of the products in the compare list so that it can be used for a 3rd party company in their hosted search. The output is in JSON format.

 

This code runs perfectly fine from a .phtml file called in a CMS page. But when it is called from outside magento in a PHP script it either throws an exception (duplicate keys) or brings other products which are not in the list of the current website visitor session. It behaves as it is mixing up all visitors sessions from the compare tables and reports of the database.

 

I am new to magento and php, and I wonder if I am missing something? The code uses nearly the same code than magento's own default template. I wonder if there is something else that needs to be done before calling the method getItemCollection from outside Magento.

 

<?php
    require_once( 'app/Mage.php' );
    umask(0);
    Mage::app('default');
    Mage::getSingleton('core/session', array('name' => 'frontend'));
    header('Content-Type: application/json');
    $_helper = Mage::helper('catalog/product_compare'); 
    $count = $_helper->getItemCount();
    echo '"compare":{';
    echo '"summary":{"count": ';
    echo $count;
    echo ' },"items": [';
    $total=0;
    if ( $count > 0 ) {
          try {          
               $_productCollection = $_helper->getItemCollection();
                        } catch (Exception $e) {
                                    echo 'Caught exception: ',  $e->getMessage(), "\n";
                        }

          foreach ($_productCollection as $_index => $product) {
                   if ($total <> 0) echo ',';
                   $total += 1;
                   echo '{ "name": "';
                   $name = $product->getName();
                   echo $name;
                   echo '", "url": "';
                   $url = $product->getProductUrl();
                   echo $url;
                   echo '", "remove_url": "';
                   $remove = $_helper->getRemoveUrl($product);
                   echo $remove;
                   echo '"}';
             } 
    } 
echo ']}';
echo '}}';
echo ')';
?>

If the user is logged in, the code works ok. 

 

Thanks!