我会推荐一种面向对象的方法来解决所有这些问题:
1)为需要将每个对象转换成的每种数据类型创建接口
interface xmlSerializable {
public function toXML();
}
interface csvSerializable {
public function toCSV();
}
interface txtSeriablizable() {
public function toTXT();
}
2)创建一个类来表示您需要为您的客户端和implement
每个接口序列化为不同格式的数据类型
class Data implements xmlSerializeable { // I only implemented one for brevity
private $id = null;
private $stuff = null;
private $otherStuff = null;
private $stuffArray = array();
public __construct($id, $stuff, $otherStuff, $stuffArray) {
$this->id = $id;
$this->stuff = $stuff;
$this->otherStuff = $otherStuff;
$this->stuffArray = $stuffArray;
}
public function getId() { return $this->id; }
public function toXML() {
$output = '<?xml version="1.0" encoding="UTF-8"?>'."\n".
'<data>'."\n\t".
'<id>'.$this->id.'</id>'."\n\t".
'<stuff>'.$this->stuff.'</stuff>'."\n\t".
'<otherStuff>'.$this->otherStuff.'</otherStuff>'."\n\t".
'<stuffArray>'."\n\t\t";
foreach($this->stuffArray as $stuff) {
$output .= '<stuff>'.$stuff.'</stuff>'."\n\t\t";
}
$output .= '</stuffArray>'."\n".
'</data>';
return $output;
}
}
现在,您可以通过创建接受 SQL 查询并返回对象数组的Data
a 来从数据库中创建对象。要序列化它们,只需调用您为每种格式实现的方法:DataFactory
Data
$df = new DataFactory($pdo);
$datas = $df->query('SELECT * FROM Data');
foreach($datas as $data) {
file_put_contents('/data/xml/'.$data->getId().'.xml', $data->toXML());
// You can add other formats here in the above fashion
}