[英]PHP - Export to CSV an array of objects
我想以CSV格式導出對象數組:
array(10) {
[0]=>
object(Produit)#228 (36) {
["id_produit":protected]=> string(4) "9999"
["reference":protected]=> string(9) "reference1"
}
[1]=>
object(Produit)#228 (36) {
["id_produit":protected]=> string(4) "8888"
["reference":protected]=> string(9) "reference2"
}
}
在這樣的事情:
id_produit | reference | ...
9999 | reference1 | ...
8888 | reference2 | ...
第一行: attribut /列的列表
另一行: Object的attribut的值
True對象的數組示例: http : //pastebin.com/8Eyf46pb
我試過這個: 將數組轉換為csv,但它對我不起作用。
是否可以這樣做(以及如何?)或者我必須在循環中編寫每個屬性?
如果您的所有屬性都是公開的,那將非常容易:
// Test class
class Produit
{
public $id_produit;
public $reference;
// Test data
public function __construct()
{
$this->id_produit = rand(1, 255);
$this->reference = rand(1, 255);
}
}
// Test data array
$array = array(new Produit(), new Produit());
// Notice, you can only use a single character as a delimiter
$delimiter = '|';
if (count($array) > 0) {
// prepare the file
$fp = fopen('test/file.csv', 'w');
// Save header
$header = array_keys((array)$array[0]);
fputcsv($fp, $header, $delimiter);
// Save data
foreach ($array as $element) {
fputcsv($fp, (array)$element, $delimiter);
}
}
但正如我所看到的,您的財產受到保護。 這意味着我們無法訪問對象外的屬性以及循環遍歷它們或使用(數組)類型轉換。 所以在這種情況下,您必須對對象進行一些更改:
// Test class
class Produit
{
// ...
public function getProperties()
{
return array('id_produit', 'reference');
}
public function toArray()
{
$result = array();
foreach ($this->getProperties() as $property) {
$result[$property] = $this->$property;
}
return $result;
}
}
然后你可以使用new方法來代替類型轉換,如下所示:
// Save data
foreach ($array as $element) {
fputcsv($fp, $element->toArray(), $delimiter);
}
還要感謝新的mehod getProperties,我們可以改變標題:
// Save header
fputcsv($fp, $array[0]->getProperties(), $delimiter);
我現在測試了以下代碼,它似乎確實有效。 反思是答案。
我試圖讓它在phpfiddle上工作,因此php:// temp但不幸的是它沒有用
<?php
class Produit
{
public $id_produit;
public $reference;
// Test data
public function __construct()
{
$this->id_produit = rand(1, 255);
$this->reference = rand(1, 255);
}
}
$array = array(new Produit(), new Produit());
$delimiter='|';
$fp=fopen('php://temp', 'w'); //replace this bit with a file name
$header=false;
foreach($array as $Produit){
$Reflection = new ReflectionClass($Produit);
$properties = $Reflection->getProperties();
$row=array();
foreach($properties as $prop){
$row[$prop->getName()] = $prop->getValue($Produit);
}
if(!$header){
fputcsv($fp, array_keys($row), $delimiter);
$header=true;
}
fputcsv($fp, $row, $delimiter);
}
//now show what has been written, you will want to remove this section
fseek($fp, 0);
fpassthru($fp);
//ends
fclose($fp);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.