将数组转换为.txt文件

时间:2010-10-20 07:34:29

标签: php arrays file format text-files

  

可能重复:
  Convert array into csv

您好,

如何将数组转换为.txt文件?

这是我的阵列:

Array
(
    [OrderList_RetrieveByContactResult] => Array
        (
            [OrderDetails] => Array
                (
                    [0] => Array
                        (
                            [entityId] => 156456
                            [orderId] => 110631
                            [orderName] => testing2
                            [statusTypeId] => 15656
                            [countryCode] => AU
                            [orderType] => 2
                            [invoiceNumber] => 1001
                            [invoiceDate] => 2010-10-19T00:00:00
                            [userID_AssignedTo] => 245454
                            [shippingAmount] => 8.95
                            [shippingTaxRate] => 0
                            [shippingAttention] => tttesst
                            [shippingInstructions] => this a test
                            [shippingOptionId] => 50161
                            [discountCodeId] => 0
                            [discountRate] => 0
                            [totalOrderAmount] => 143.8
                            [directDebitTypeId] => 0
                            [directDebitDays] => 0
                            [isRecur] => 
                            [nextInvoiceDate] => 0001-01-01T00:00:00
                            [endRecurDate] => 0001-01-01T00:00:00
                            [cycleTypeID] => 1
                            [createDate] => 2010-10-19T05:40:00
                            [lastUpdateDate] => 2010-10-19T05:40:00
                            [deleted] => 
                            [products] => Array
                                (
                                    [Product] => Array
                                        (
                                            [productId] => 455
                                            [productCode] => 
                                            [productDescription] => testtest
                                            [units] => 3
                                            [unitPrice] => 44.95
                                            [unitTaxRate] => 0
                                            [totalProductPrice] => 134.85
                                            [productName] => Skin Support Tablets
                                        )
                                )

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

                        )

                    [1] => Array
                        (
                            [entityId] => 315456
                            [orderId] => 321321
                            [orderName] => testing
                            [statusTypeId] => 3213
                            [countryCode] => AU
                            [orderType] => 2
                            [invoiceNumber] => 1002
                            [invoiceDate] => 2010-10-19T00: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-19T18:36:00
                            [deleted] => 
                            [products] => Array
                                (
                                    [Product] => Array
                                        (
                                            [productId] => 11564
                                            [productCode] => 
                                            [productDescription] => 
                                            [units] => 10
                                            [unitPrice] => 39.95
                                            [unitTaxRate] => 0
                                            [totalProductPrice] => 399.5
                                            [productName] => Acne Clearing Gel
                                        )

                                )

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

                                )

                        )

                )

        )

)

3 个答案:

答案 0 :(得分:11)

如果您希望它是可解析的,可以使用

  • var_export - 输出或返回变量的可解析字符串表示

示例

file_put_contents('array.txt', var_export($array, TRUE));

如果您希望它在您的问题中显示,请将TRUE作为第二个参数传递给print_r

file_put_contents('array.txt', print_r($array, TRUE));

编辑您在评论中提到您希望将数组转换为CSV文件。这更难。您的数组是嵌套的,而CSV文件基本上是单个暗淡的数组,例如

array('k1' => 'v1', 'k2' => 'v2', ... , 'kn' => 'vn');

将等同于CSV文件,其中第一行是数组键,第二行是值。

k1; k2; ...; kn
v1; v2; ...; vn

单个dims数组通常位于另一个数组中,因此您有一个这样的集合:

array(
   array('k1' => 'v1', 'k2' => 'v2', ... , 'kn' => 'vn'),
   array('k1' => 'v1', 'k2' => 'v2', ... , 'kn' => 'vn')
);

在这里,您必须首先获取密钥,然后仅从后续行的数组中获取值,例如

k1; k2; ...; kn
v1; v2; ...; vn
v1; v2; ...; vn

问题是,你的数组嵌入得更深。你会把地址数组放在哪里?唯一可行的方法是遍历数组并仅获取包含标量类型的那些键和值并线性化任何嵌套数组,例如。

array(
   array('k1' => 'v1', 'k2' => 'v2', ... , 'kn' => array( 'skn' => 'svn' ) ),
   array('k1' => 'v1', 'k2' => 'v2', ... , 'kn' => array( 'skn' => 'svn' ) ),
);

必须变成

k1; k2; ...; skn
v1; v2; ...; svn
v1; v2; ...; svn

如果不清楚,这里有一个例子:

Flattening a Multidimensional Array for use in a CSV file

幸运的是,这可以通过迭代器实现:

$orderDetails = $array['OrderList_RetrieveByContactResult']['OrderDetails'];
foreach( $orderDetails as $key => $details ) {

    $iterator = new RecursiveIteratorIterator(
            new RecursiveArrayIterator($details));

    if($key === 0) {
        $keys = array();
        foreach($iterator as $k => $v) {
            $keys[] = $k;
        }
        echo implode(';', $keys);
    }

    $values = array();
    foreach($iterator as $val) {
        $values[] = $val;
    }
    echo PHP_EOL, implode(';', $values);
}

以上代码应输出所描述的格式。有关示例,请参阅http://www.ideone.com/I70dD

要将其写入文件,您可以将其汇编为字符串变量,然后将file_put_contents汇总一次,或者使用filepointer并逐行编写。如果你不implode但是迭代$flattened数组,你也可以使用fputcsv

答案 1 :(得分:7)

如果要将变量保存在文本文件中,可以使用serialize() / unserialize()函数:

$data = array(1, 2, 3, '');
$toBeSaved = serialize($data);
file_put_contents('somefile.txt', $toBeSaved);

恢复它......

$toBeRestored = file_get_contents('somefile.txt');
$data = unserialize($toBeRestored);

答案 2 :(得分:1)

也许你想要的是fputcsv