Search code examples
phpstringencapsulationquote

Enclose PHP output in quotation marks


we have a PHP script that exports orders to .csv files. The system we are exporting too requires each field to be encapsulated in quote marks.

Here is the code where we set each field.

$order_data = array(
        'type'                => "H",
        'order_type'            => 'HOME',
        'order_date'          => $order->order_date,
        'account_code'          => "REAL", 
        'document_reference'    =>'',
        'reference1'=>'',
        'reference2'=>'',
        'delivery_addess_code'=> '',
        'billing_first_name'  => $order->billing_first_name ." ".$order->billing_last_name,
        'billing_address_1'   => $order->billing_address_1 ." ".$order->billing_address_2,
        'billing_postcode'    => $order->billing_postcode,
        'delivery_tel_no'=>   $order->billing_phone,
        'delivery_contact'=>   $order->billing_first_name,

This outputs;

H,HOME,"2015-05-13 13:19:46",REAL,,,,,"Ben Bull","Address 1 Address2",

Some are surround by "" and some aren't how do we get them all to be?


Solution

  • For CSV output, you need to enclose all the values with double quotes. In addition, if the values have double quotes inside them you need to escape those double quotes by using two consecutive double quotes. That's how CSV works.

    Check this PHP function below.

    function makeCSV($value) {
        //Encloses each token (Before and after)
        $CSV_TOKEN_ENCLOSER = '"';
    
        //Used to escape the enclosing character if inside the token
        $CSV_TOKEN_ENCLOSER_ESCAPER = '""';
    
        //Escape the encloser inside the value
        $csv_value = str_replace($CSV_TOKEN_ENCLOSER, $CSV_TOKEN_ENCLOSER_ESCAPER, $value);
    
        //Enclose the value
        $csv_value .= $CSV_TOKEN_ENCLOSER . $csv_value . $CSV_TOKEN_ENCLOSER;
    
        //Return
        return $csv_value;
    }
    

    This does the job as I've explained in the first paragraph. You can use it as such in your case:

    $order_data = array(
        'type'       => makeCSV("H"),
        'order_type' => makeCSV('HOME'),
        'order_date' => makeCSV($order->order_date),
        ...
    );
    

    However, it looks like you have code that's enclosing the values from your order objects within quotes automatically for you. I suggest you avoid that code, replace that with the usage of the makeCSV function presented above, and then finally just use a standard PHP implode call to get your CSV like this:

    $comma_separated_csv = implode(",", $order_data);
    

    Hope this helps.

    Cheers.