It would be pretty easy if all of your properties were publicly available:
class Produit
{
public $id_produit;
public $reference;
public function __construct()
{
$this->id_produit = rand(1, 255);
$this->reference = rand(1, 255);
}
}
$array = array(new Produit(), new Produit());
$delimiter = '|';
if (count($array) > 0) {
$fp = fopen('test/file.csv', 'w');
$header = array_keys((array)$array[0]);
fputcsv($fp, $header, $delimiter);
foreach ($array as $element) {
fputcsv($fp, (array)$element, $delimiter);
}
}
, , . , , (). :
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;
}
}
typecasting toArray :
foreach ($array as $element) {
fputcsv($fp, $element->toArray(), $delimiter);
}
getProperties :
fputcsv($fp, $array[0]->getProperties(), $delimiter);