I have a PersonMapper that reads from a DB and creates Person objects (PHP Slim Framework 3):
<?php
class PersonMapper extends Mapper {
public function getPersons() {
$stmt = $this->db->query("SELECT p.id, p.firstname, p.pastname FROM persons p");
$results = [];
while($row = $stmt->fetch()) {
$results[] = new Person($row);
}
return $results;
}
}
class Person implements ArrayAccess {
protected $id;
protected $firstname;
protected $lastname;
public function __construct(array $data) {
// no id if we're creating
if(isset($data['id'])) { $this->id = $data['id']; }
$this->firstname= $data['firstname'];
$this->lastname= $data['lastname'];
}
public function getId() { return $this->id; }
public function getFirstname() { return $this->firstname; }
public function getLastname() { return $this->lastname; }
public function offsetExists($offset) {
return array_key_exists($offset, $this->asArray());
}
public function offsetGet($offset) {
return $this->offsetExists($offset) ? $this->asArray()[$offset]:NULL;
}
public function offsetSet($offset, $value) {
$this->asArray()[$offset] = $value;
}
public function offsetUnset($offset) {
if ($this->offsetExists($offset)) {
$_array = $this->asArray();
unset($_array[$offset]);
}
}
public function asArray() {
return array(
'id' => $this->id,
'firstname' => $this->firstname,
'kurzbezeichnung' => $this->lastname);
}
}
I am now able to get an array of person objects:
$mapper = new PersonMapper($this->db);
$persons= $mapper->getPersons();
Now I want to put the list of persons into an excel file:
$excelDoc = new PHPExcel();
$excelDoc->setActiveSheetIndex(0);
$excelDoc->getActiveSheet()->fromArray($persons, null, 'A1');
$writer = PHPExcel_IOFactory::createWriter($excelDoc, 'Excel2007');
$writer->save("persons.xlsx");
Unfortunately, PHPExcel can't handle this kind of data structure:
Catchable fatal error: Object of class Person could not be converted to
string in /path/to/src/vendor/phpoffice/phpexcel/Classes/
PHPExcel/Cell/DefaultValueBinder.php on line 65
Any help is greatly appreciated!