Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/268.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 将数组转换为csv_Php_Arrays_Csv - Fatal编程技术网

Php 将数组转换为csv

Php 将数组转换为csv,php,arrays,csv,Php,Arrays,Csv,如何将数组转换为CSV文件 这是我的阵列: stdClass Object ( [OrderList_RetrieveByContactResult] => stdClass Object ( [OrderDetails] => stdClass Object ( [entityId] => 1025298 [orde

如何将数组转换为CSV文件

这是我的阵列:

stdClass Object
(

    [OrderList_RetrieveByContactResult] => stdClass Object
        (
            [OrderDetails] => stdClass Object
                (
                    [entityId] => 1025298
                    [orderId] => 10952
                    [orderName] => testing
                    [statusTypeId] => 4652
                    [countryCode] => AU
                    [orderType] => 1
                    [invoiceNumber] => 0
                    [invoiceDate] => 0001-01-01T00:00:00
                    [userID_AssignedTo] => 11711
                    [shippingAmount] => 8.95
                    [shippingTaxRate] => 0
                    [shippingAttention] => 
                    [shippingInstructions] => 
                    [shippingOptionId] => 50161
                    [discountCodeId] => 0
                    [discountRate] => 0
                    [totalOrderAmount] => 408.45
                    [directDebitTypeId] => 0
                    [directDebitDays] => 0
                    [isRecur] => 
                    [nextInvoiceDate] => 0001-01-01T00:00:00
                    [endRecurDate] => 0001-01-01T00:00:00
                    [cycleTypeID] => 1
                    [createDate] => 2010-10-08T18:40:00
                    [lastUpdateDate] => 2010-10-08T18:40:00
                    [deleted] => 
                    [products] => stdClass Object
                        (
                            [Product] => stdClass Object
                                (
                                    [productId] => 674975
                                    [productCode] => 
                                    [productDescription] => 
                                    [units] => 10
                                    [unitPrice] => 39.95
                                    [unitTaxRate] => 0
                                    [totalProductPrice] => 399.5
                                    [productName] => Acne Clearing Gel
                                )

                        )

                    [addresses] => stdClass Object
                        (
                            [Address] => stdClass Object
                                (
                                    [addressTypeID] => 8
                                    [addressLine1] => Cebu City
                                    [city] => Cebu
                                    [zipcode] => 6000
                                    [state] => 
                                    [countryCode] => PH
                                )

                        )

                )

        )

)
函数数组\u 2\u csv($array){
$csv=array();
foreach($数组作为$项){
if(is_数组($item)){
$csv[]=array_2_csv($item);
}否则{
$csv[]=$item;
}
}
返回内爆(“,”,$csv);
} 
$csv\u data=array\u 2\u csv($array);
回声“;
打印(csv数据);
回声';

我正在为此使用以下函数;这是根据fputscsv评论中的一个man条目改编的。你可能想把这个阵列展平;不知道如果你进入多维空间会发生什么

<?
    $data = array(
        array( 'row_1_col_1', 'row_1_col_2', 'row_1_col_3' ),
        array( 'row_2_col_1', 'row_2_col_2', 'row_2_col_3' ),
        array( 'row_3_col_1', 'row_3_col_2', 'row_3_col_3' ),
    );
?>

我的解决方案要求阵列的格式与问题中提供的不同:

<?
    function outputCSV($data) {
        $outputBuffer = fopen("php://output", 'w');
        foreach($data as $val) {
            fputcsv($outputBuffer, $val);
        }
        fclose($outputBuffer);
    }
?>

我们定义了我们的功能:

<?
    $filename = "example";

    header("Content-type: text/csv");
    header("Content-Disposition: attachment; filename={$filename}.csv");
    header("Pragma: no-cache");
    header("Expires: 0");

    outputCSV($data);
?>

然后,我们将数据输出为CSV:

// Create Some data
<?php
    $data = array(
        array( 'row_1_col_1', 'row_1_col_2', 'row_1_col_3' ),
        array( 'row_2_col_1', 'row_2_col_2', 'row_2_col_3' ),
        array( 'row_3_col_1', 'row_3_col_2', 'row_3_col_3' ),
    );


// Create a stream opening it with read / write mode
$stream = fopen('data://text/plain,' . "", 'w+');

// Iterate over the data, writting each line to the text stream
foreach ($data as $val) {
    fputcsv($stream, $val);
}

// Rewind the stream
rewind($stream);

// You can now echo it's content
echo stream_get_contents($stream);

// Close the stream 
fclose($stream);


我已经在几个项目中使用了它,并且效果很好。我应该注意到,
outputcv
代码比我更聪明,所以我肯定我不是原始作者。不幸的是,我不知道我从哪里得到了它,所以我不能把它归功于谁。

对kingjeffrey上面的解决方案进行了一点修改,用于在模板中创建和回显CSV(即-大多数框架将启用输出缓冲,并且需要在控制器中设置标题等)

//创建一些数据

也许四年后有点晚了哈哈。。。但我一直在寻找解决方案做对象到CSV,然而大多数解决方案实际上是数组到CSV

经过一些修改后,这里是我将对象转换为CSV的解决方案,我认为这非常好。希望这能帮助其他人

blah,blah,blah
blah,blah,blah
请注意,要使
$key=>$value
工作,您的
对象的属性必须是公共的,私有的属性将不会被获取

最终的结果是你会得到这样的结果:

Array
(
    [0] => Array
        (
            [a] => "a"
            [b] => "b"
        )

    [1] => Array
        (
            [a] => "a2"
            [b] => "b2"
        )

    [2] => Array
        (
            [a] => "a3"
            [b] => "b3"
        )

    [3] => Array
        (
            [a] => "a4"
            [b] => "b4"
        )

    [4] => Array
        (
            [a] => "a5"
            [b] => "b5"
        )

)

保罗的回答很好。我对此做了一个小小的扩展,如果您有这样一个多维数组(这很常见),这非常有用:

所以我从上面取了Paul的函数:

function a2c($array, $glue = "\n")
{
    $ret = [];
    foreach ($array as $item) {
        $ret[] = arrayToCsv($item);
    }
    return implode($glue, $ret);
}
并补充说:

$csv = a2c($array);
所以你可以打电话:


如果你想要一个特殊的行尾,你可以使用可选的参数“glue”来完成这个任务。

根据接受的答案添加一些改进

  • PHP7.0严格类型
  • PHP7.0类型声明和返回类型声明
  • 存储模块\r\n\t
  • 即使$encloseAll为TRUE,也不要使用空字符串
  • /**
    *将行(作为字段数组传递)格式化为CSV,并将CSV作为字符串返回。
    *改编自https://www.php.net/manual/en/function.fputcsv.php#87120
    */
    函数arrayToCsv(数组$fields,字符串$delimiter=';',字符串$enclosure=''”,bool$enclosureAll=false,bool$nullToMysqlNull=false):字符串{
    $delimiter_esc=preg_quote($delimiter,'/');
    $enclosure_esc=preg_quote($enclosure,“/”);
    $output=[];
    foreach($fields作为$field){
    如果($field==null&&$nullToMysqlNull){
    $output[]='NULL';
    继续;
    }
    //将包含$delimiter、$enclosure或空格、换行符的字段括起来
    $field=strval($field);
    if(strlen($field)&($encloseAll | | | | preg| match(/(?:${delimiter|esc}}|${enclosure| esc}| \s | \r | \n | \t)/“,$field)){
    $output[]=$enclosure.str_replace($enclosure,$enclosure.$enclosure,$field)。$enclosure;
    }否则{
    $output[]=$field;
    }
    }
    返回内爆($delimiter,$output);
    }
    
    你可能想用你的代码所用的任何语言来标记这个问题。这将帮助你在你的问题上获得更多的眼球。:)我不认为有一种方法可以在CSV中呈现多维性,是吗?另请参见将
    fputcsv()
    ob_start();$df=fopen(“php://output“,‘w’);fclose($df);返回ob_get_clean()
    。你好,Paulrajj,非常感谢。你真的帮了我的忙。你的帅哥!:DHi Paul,谢谢,这真的帮了我很多。你最好的!:DHi,这对我很有用。但是我有一个问题,我怎么才能在一行之后创建新行?我在for循环中添加了一个计数器,如果它是第一个索引的结尾,我会像这样附加一行新行$output[$i]。=“\r\n"; 它创建了一个新行,但也在下一行中添加了一个新单元格。存在一种边缘情况,即如果
    $fields
    数组中的最后一个值是空字符串,则会将其丢弃。因此,如果数组长度为3个元素,且最后一个元素为空字符串,则将在空字符串之前获取值,该值由2个分隔符分隔,而不是指示最后一个值为空所需的3个分隔符。如果不允许文件创建权限,则此解决方案非常有用
    Array
    (
        [0] => Array
            (
                [a] => "a"
                [b] => "b"
            )
    
        [1] => Array
            (
                [a] => "a2"
                [b] => "b2"
            )
    
        [2] => Array
            (
                [a] => "a3"
                [b] => "b3"
            )
    
        [3] => Array
            (
                [a] => "a4"
                [b] => "b4"
            )
    
        [4] => Array
            (
                [a] => "a5"
                [b] => "b5"
            )
    
    )
    
    /**
      * Formats a line (passed as a fields  array) as CSV and returns the CSV as a string.
      * Adapted from http://us3.php.net/manual/en/function.fputcsv.php#87120
      */
    function arrayToCsv( array &$fields, $delimiter = ';', $enclosure = '"', $encloseAll = false, $nullToMysqlNull = false ) {
        $delimiter_esc = preg_quote($delimiter, '/');
        $enclosure_esc = preg_quote($enclosure, '/');
    
        $output = array();
        foreach ( $fields as $field ) {
            if ($field === null && $nullToMysqlNull) {
                $output[] = 'NULL';
                continue;
            }
    
            // Enclose fields containing $delimiter, $enclosure or whitespace
            if ( $encloseAll || preg_match( "/(?:${delimiter_esc}|${enclosure_esc}|\s)/", $field ) ) {
                $output[] = $enclosure . str_replace($enclosure, $enclosure . $enclosure, $field) . $enclosure;
            }
            else {
                $output[] = $field;
            }
        }
    
        return implode( $delimiter, $output );
    }
    
    function a2c($array, $glue = "\n")
    {
        $ret = [];
        foreach ($array as $item) {
            $ret[] = arrayToCsv($item);
        }
        return implode($glue, $ret);
    }
    
    $csv = a2c($array);