Export products in Json format in two languages Opencart

116 Views Asked by At

I created this in the controller to export the products in json format, but I only get them in 1 language, I need them in two languages What could I do in this case I need help!

    <?php
         class ControllerApiProduct extends Controller
     {
      public function index()
    {
    $this->load->language('api/cart');
    $this->load->model('catalog/product');
    $this->load->model('tool/image');
    $json = array();
    $json['products'] = array();
    $filter_data = array();
 
    $results = $this->model_catalog_product->getProducts($filter_data);
    foreach ($results as $result) {
       
        $data['products'][] = array(
            'name' => $result['name'],
           
        );
    }
    $json['products'] = $data['products'];
    $this->response->addHeader('Content-Type: application/json');
    $this->response->setOutput(json_encode($json));
   }
}
1

There are 1 best solutions below

0
jcord04 On

METHOD 1
Set the language id after you're current foreach and fetch the data again. $this->config->set('config_language_id', LANGUAGE_ID_HERE). Ensure you reset it afterwards.


METHOD 2
It would be more efficient to update the model method so you can pass an array of language ids getProducts() in the file catalog/model/catalog/product.php

Example

public function getProducts(array $data = [], array $language_ids = []): array {

and change the query to something like this where it will fetch records matching the array of given language ids

From

WHERE pd.`language_id` = '" . (int)$this->config->get('config_language_id') . "' AND p.`status` = '1' AND p.`date_available` <= NOW() AND p2s.`store_id` = '" . (int)$this->config->get('config_store_id') . "'";

To

WHERE pd.`language_id` IN (" . !empty($language_ids) ? implode(',', $language_ids) : (int) $this->config->get('config_language_id') . ") AND p.`status` = '1' AND p.`date_available` <= NOW() AND p2s.`store_id` = '" . (int)$this->config->get('config_store_id') . "'";