如果您的所有属性都是公开的,那将非常容易:
// 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);