0

I have created one app using php which is used for download details as a .csv file format from shopify store.

Now all the details got it, but details which are special characters are not working fine.

I referenced a lot of stack overflow questions related my issues, but they are not helping me.

SAMPLE OUTPUT: enter image description here

PHP:

<?php
require_once 'lib/shopify.php';
//require_once 'csv.php';
function csvToJson($csv)
{
    $rows = explode("\n", trim($csv));
    $csvarr = array_map(function($row)
    {
        $keys = array(
            'var0',
            'var1',
            'var2',
            'var3',
            'var4',
            'var5',
            'var6',
            'var7',
            'var8',
            'var9'
        );
        return array_combine($keys, str_getcsv($row));
    }, $rows);
    $json   = json_encode($csvarr);

    return $json;
}

$t     = "bac2486aa2b31aa5aed1fdd62e77a4ae";
$sc    = new ShopifyClient("mine-329.myshopify.com/", $t, API_KEY, SECRET);
$order = array();
if (!isset($t)) {
    if (!isset($_GET['signature'])) {
        $url = $sc->getAuthorizeUrl("read_orders");
        header('Location: ' . $url);
    }
    if (isset($_GET['code'])) {
        $accTok = $sc->getAccessToken($_GET['code']);
        echo "token = " . $accTok;
        exit;
        $orders = $sc->call('GET', 'admin/orders.json', array(
            'published_status' => 'published'
        ));
        foreach ($orders as $order) {
            echo $order['id'];
            echo $order['email'];
        }
    }
}
if (isset($t)) {
    $orders               = $sc->call('GET', 'admin/orders.json', array(
        'published_status' => 'published'
    ));
    $myarray              = array();
    $list[]               = array(
        'Name',
        'Email',
        'Financial Status',
        'Paid at',
        'Fulfillment Status',
        'Fulfilled at',
        'Accepts Marketing',
        'Currency',
        'Subtotal',
        'Shipping',
        'Taxes',
        'Total',
        'Discount code',
        'Discount Amount',
        'Shipping Method',
        'Created at',
        'Lineitem quantity',
        'Lineitem name',
        'Lineitem price',
        'Lineitem compare at price',
        'Lineitem sku',
        'Lineitem requires shipping',
        'Lineitem taxable',
        'Lineitem fulfillment status',
        'Billing Name',
        'Billing Street',
        'Billing Address1',
        'Billing Address2',
        'Billing Company',
        'Billing City',
        'Billing Zip',
        'Billing Province',
        'Billing Country',
        'Billing Phone',
        'Shipping Name',
        'Shipping Street',
        'Shipping Address1',
        'Shipping Address2',
        'Shipping Company',
        'Shipping City',
        'Shipping Zip',
        'Shipping Province',
        'Shipping Country',
        'Shipping Phone',
        'Notes',
        'Note Attributes',
        'VAT',
        'Cancelled at',
        'Payment Method',
        'Payment Reference',
        'Refunded Amount',
        'Vendor',
        'Id',
        'Tags'
    );
    $list                 = array_filter($list);
    $empty_note_attribute = "";
    if (empty($order['note_attributes'])) {
        $empty_note_attribute = "";
    } else {
        $empty_note_attribute = $order['note_attributes'];
    }
    $empty_discount_codes = "";
    if (empty($order['discount_codes'])) {
        $empty_discount_codes = "";
    } else {
        $empty_discount_codes = $order['discount_codes'];
    }
    foreach ($orders as $order) {
        $str          = file_get_contents('slim-2.json'); //give the address of json file  
        $str          = mb_convert_encoding($str, 'UTF-8');
        $json_country = json_decode($str, true);
        //Here is the problem you are passing `$str` but you should pass `$json_country`
        if (is_array($json_country)) {
            foreach ($json_country as $key => $value) {
                if (array_search(trim($order['billing_address']['country']), $value)) // Added trim 
                    {
                    $order['billing_address']['country'] = $value['alpha-2'];
                }
                if (isset($order['shipping_address']['country'])) {
                    if (array_search(trim($order['shipping_address']['country']), $value)) // Added trim         
                        {
                        $order['shipping_address']['country'] = $value['alpha-2'];
                    }
                }
            }
        }

        $csv        = file_get_contents('states.csv');
        $json       = csvToJson($csv);
        $json_state = json_decode($json, true);
        $bilProvin  = trim($order['billing_address']['province']);
        $shpProvin  = '';
        if (isset($order['shipping_address'])) {
            $shpProvin = $order['shipping_address']['province'];

        }
        foreach ($json_state as $keys) {
            if (array_search($bilProvin, $keys)) // Added trim 
                {
                $order['billing_address']['province'] = substr($keys['var1'], 3);
            }
            if (isset($order['shipping_address'])) {

                if (array_search($shpProvin, $keys)) {

                    $order['shipping_address']['province'] = substr($keys['var1'], 3);
                }
            }
        }




        $orders_lineitem = $order['line_items'];
        $lineitemcount   = 0;
        foreach ($orders_lineitem as $lineitem) {
            /*
            Fulfillment Status
            */
            $fulfill_status = "";
            if (empty($order['fulfillment_status'])) {
                $fulfill_status = "pending";
            } else {
                $fulfill_status = $order['fulfillment_status'];
            }
            /*
            Lineitem Fulfillment Status
            */
            $fulfillment_status = '';
            if (empty($order['fulfillments'][0]['created_at'])) {
                $fulfillment_status = "pending";
            } else {
                $fulfillment_status = $order['line_items'][0]['fulfillment_status'];
            }
            $variants          = "";
            $variants          = $sc->call('GET', "admin/variants/" . $lineitem['variant_id'] . ".json", array(
                'published_status' => 'published'
            ));
            $requires_shipping = "false";
            if ($lineitem['requires_shipping']) {
                $requires_shipping = "true";
            }
            $lineitem_taxable = "false";
            if ($lineitem['taxable']) {
                $lineitem_taxable = "true";
            }
            //** Accepts Marketting **

            $accepts_marketting = "no";
            if ($order['buyer_accepts_marketing']) {
                $accepts_marketting = "yes";
            }
            $shipping = '';
            if (count($order['shipping_lines']) > 0) {
                $shipping = $order['shipping_lines'][0]['price'];
            }
            /* 
            Fulfilled at
            */
            $created_at = '';
            if (count($order['fulfillments']) > 0) {
                $created_at = $order['fulfillments'][0]['created_at'];
            }

            /*
            total tax
            */
            $total_tax = '';
            if (count($order['line_items'][0]['tax_lines']) > 0) {
                $total_tax = $order['line_items'][0]['tax_lines'][0]['price'];
            }

            /*
            Payment reference
            */

            $payment = '';
            if ($order['checkout_id']) {
                $payment = sprintf('c%s.1', $order['checkout_id']);
            }

            /*  
            Refunded Amount 
            */
            $refund_price = '';
            if (count($order['refunds']) > 0) {
                foreach ($order['refunds'] as $refund) {
                    if (count($refund['transactions']) > 0) {
                        $refund_price += $refund['transactions'][0]['receipt']['paid_amount'];
                    }
                }
            }
            if ('pending' == $fulfill_status || 'partial' == $fulfill_status) {
                $created_at = '';
            }

            if ($lineitemcount == 0) {
                array_push($list, array(
                    $order['name'],
                    $order['email'],
                    $order['financial_status'],
                    (($order['financial_status'] != 'partially_refunded') && ($order['financial_status'] != 'refunded') && ($order['financial_status'] != 'authorized') ? $order['created_at'] : null),
                    $fulfill_status,
                    $created_at,
                    $accepts_marketting,
                    $order['currency'],
                    $order['subtotal_price'],
                    (($shipping > 0) ? $shipping : 0),
                    $order['total_tax'],
                    $order['total_price'],
                    $empty_discount_codes,
                    $order['total_discounts'],
                    (($shipping > 0) ? $order['shipping_lines'][0]['code'] : null),
                    $order['created_at'],
                    $lineitem['quantity'],
                    $lineitem['name'],
                    $lineitem['price'],
                    $variants['compare_at_price'],
                    $lineitem['sku'],
                    $requires_shipping,
                    $lineitem_taxable,
                    $fulfillment_status,
                    $order['billing_address']['name'],
                    $order['billing_address']['address1'],
                    $order['billing_address']['address1'],
                    $order['billing_address']['address2'],
                    $order['billing_address']['company'],
                    $order['billing_address']['city'],
                    $order['billing_address']['zip'],
                    $order['billing_address']['province'],
                    $order['billing_address']['country'],
                    $order['billing_address']['phone'],
                    (($shipping > 0) ? $order['shipping_address']['name'] : null),
                    (($shipping > 0) ? $order['shipping_address']['address1'] : null),
                    (($shipping > 0) ? $order['shipping_address']['address1'] : null),
                    (($shipping > 0) ? $order['shipping_address']['address2'] : null),
                    (($shipping > 0) ? $order['shipping_address']['company'] : null),
                    (($shipping > 0) ? $order['shipping_address']['city'] : null),
                    (($shipping > 0) ? $order['shipping_address']['zip'] : null),
                    (($shipping > 0) ? $order['shipping_address']['province'] : null),
                    (($shipping > 0) ? $order['shipping_address']['country'] : null),
                    (($shipping > 0) ? $order['shipping_address']['phone'] : null),
                    $order['note'],
                    $empty_note_attribute,
                    $total_tax,
                    $order['cancelled_at'],
                    $order['payment_details']['credit_card_company'],
                    $payment,
                    (($refund_price > 0) ? $refund_price : 0),
                    $lineitem['vendor'],
                    $order['id'],
                    $order['tags']
                ));
            } else {
                array_push($list, array(
                    $order['name'],
                    $order['email'],
                    '',
                    '',
                    '',
                    '',
                    '',
                    '',
                    '',
                    '',
                    '',
                    '',
                    $empty_discount_codes,
                    '',
                    '',
                    $order['created_at'],
                    $lineitem['quantity'],
                    $lineitem['name'],
                    $lineitem['price'],
                    $variants['compare_at_price'],
                    $lineitem['sku'],
                    $requires_shipping,
                    $lineitem_taxable,
                    $fulfillment_status,
                    '',
                    '',
                    '',
                    '',
                    '',
                    '',
                    '',
                    '',
                    '',
                    '',
                    '',
                    '',
                    '',
                    '',
                    '',
                    '',
                    '',
                    '',
                    '',
                    '',
                    '',
                    '',
                    '',
                    '',
                    '',
                    '',
                    '',
                    $lineitem['vendor'],
                    '',
                    $order['tags']
                ));
            }
            $lineitemcount++;
        }
    }
    $order  = $_GET;
    $list[] = array_to_csv_download($myarray, // this array is going to be the second row
        "numbers.csv");
    $list   = array_filter($list);
    array_to_csv_download($list);
    header("Content-type: text/csv; charset=UTF-16LE");
    header("Content-Disposition: attachment; filename=file.csv");
    header("Pragma: no-cache");
    header("Expires: 0");
}
function array_to_csv_download($list)
{
    $output = fopen("php://output", "w");
    foreach ($list as $row) {
        fputcsv($output, $row);
        //print_r($row); die;
    }
    fclose($output);
}
?>

How to fix this problem, and what is the exact function to use?

Any help would be appreciated!!!

Thank you.

Fabricator
  • 12,722
  • 2
  • 27
  • 40
user3750829
  • 1
  • 1
  • 3
  • 1
    What particular problem are you having within the huge block of code you posted. Can you narrow down specifically where in this code your concerns are? – Mike Brant Jun 18 '14 at 04:48
  • @MikeBrant: At the bottom of my code,I want know the exact function is used for download csv file with special characters. can you help me? – user3750829 Jun 18 '14 at 04:52
  • http://www.php.net//manual/en/function.mb-convert-encoding.php Ideally you want to use UTF-8. When opening CSV with MS Excel you have to choose proper encoding as well. This can be troubling because i guess that default Excel's encoding is diffrent for each region, for e.g. polish version uses Windows-1252. – superrafal Jun 18 '14 at 04:53
  • @superrafal: I m new to php, may i know where is the exact place to edit my code? – user3750829 Jun 18 '14 at 04:56
  • In array_to_csv() function. fputcsv($output, mb_convert_encoding($row, "UTF-8")); You may have to try diffrent encodings and also additional param (look up php doc link I gave You). – superrafal Jun 18 '14 at 05:12
  • @superrafal: I want 2-name character from which names are with special characters, say for example Tamilnadu is one of the state in INDIA, so 2-name character of tamilnadu is 'TN', so i got it.but words which are special characters, can't able to get like that,(e.g.,Álava) is displayed as full name. – user3750829 Jun 18 '14 at 05:28

1 Answers1

1

change your header from

header("Content-type: text/csv; charset=UTF-16LE");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");

to

header('Content-Encoding: UTF-8');
header('Content-type: text/csv; charset=UTF-8');
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
echo "\xEF\xBB\xBF"; // UTF-8 BOM

copied from here

Community
  • 1
  • 1
Fabricator
  • 12,722
  • 2
  • 27
  • 40
  • I don't want print special character, i need change to normal word from special character, for example Álava(A is with special character) so i need 2-name character of alava(i.e., VI) but what i got, like as my image posted above. – user3750829 Jun 18 '14 at 05:07
  • @user3750829, did you at least try it? – Fabricator Jun 18 '14 at 05:08
  • In this case you need to write some kind of 'converter' function and use it like this: fputcsv($output, convertSpecialChar($row)). This function should chceck for special characters in $row and return converted string. – superrafal Jun 19 '14 at 06:58