XML product feed category problem

I have written a php script so I can produce for my Magento 1.9.3.8 an xml product feed to send my products to another price comparison site. I have a problem with the category path of my products which is sent in the xml. It seems to be “random”. With “random” I mean that my category’s structure is complicated. All products are in categories by its kind but they are also in Brands category and in some other categories like Sales category. For example:

Product “X” which is a mobile phone

This product is in category:

Root Catalog / Mobile Phones

And also in categories:

Root Catalog / Samsung(Brand) / Mobile Phones

Root Catalog / Low Price Offers / Mobile Phones (Sale category)

I am using this code to get the category path and id in my xml:

 }  private function getCategories($  oProduct) {     $  aIds = $  oProduct->getCategoryIds();     $  aCategories = array();     $  catPath = array();     $  aCategories['bread'] = '';      $  catexclude_array = array();     $  catexclude_array = explode(',', $  this->oConfig->general->catexclude);      foreach($  aIds as $  iCategory){     if (!in_array($  iCategory, $  catexclude_array)) {     $  aCategories['bread'] = '';         $  oCategory = Mage::getModel('catalog/category')->load($  iCategory);         $  aCategories['cid'] = $  oCategory->getId();          $  aCategories['catpath'] = $  oCategory->getPath();         $  catPath = explode('/', $  aCategories['catpath']);         foreach($  catPath as $  cpath){         $  pCategory = Mage::getModel('catalog/category')->load($  cpath);          if($  pCategory->getName() !='Root Catalog' && $  pCategory->getName()!='Default Category'&& $  pCategory->getName()!='ΚΑΤΗΓΟΡΙΕΣ'&& $  pCategory->getName()!=''){          if (!in_array($  pCategory->getId(), $  catexclude_array)) {          $  aCategories['bread'] .= $  pCategory->getName() . ' > ';          }          }         }         $  aCategories['bread'] = "Αρχική > " . mb_substr(trim(substr($  aCategories['bread'],0,-3)),0,299,'UTF-8');     }                }      return $  aCategories; } 

But it returns random category in xml. Product “X” I mentioned before and Product “2X” which are both in the categories I described, in xml The “X” is at category:

Root Catalog / Mobile Phones

and The “2X” is at category:

Root Catalog / Low Price Offers

In the xml I need the category describes the kind of the product. And this isn’t suitable.

What am I doing wrong please?