以多种格式输出数据库信息


Outputting database information in multiple formats

我目前正在创建一个CMS,CMS的主要功能之一是数据馈送系统。该网站将把其一个数据库的内容转移到大量的上市网站。每个网站都有自己的规范来格式化这些信息,我的任务是创建一个后端,可以用来为非程序员轻松修改和添加数据源。

到目前为止,在我收到的格式中,有三种文件类型,XML、CSV和TXT。即使在这些文件类型中,也有不同的格式标准,不同的字段顺序,有些有引号,有些没有,等等。我对此感到困惑了一段时间,下面是我的解决方案:

  • 每个提要都将有一个模板存储在一个单独的数据库表中。模板将由提要所需的任何结构(XML、CSV、TXT)和占位符值(例如{{NAME}})组成。然后,脚本将循环遍历每个数据库条目,用变量值替换占位符,并使用正确的文件扩展名保存完成的文档

我的问题是弄清楚如何使用一个PHP文件保存多个文件(也许从另一个PHP文件多次调用同一个文件?),此外,如何保存这样的不同文件类型。基本上,我该如何设置扩展名并保存文件?

您可以像保存第一个文件一样保存多个文件。

如果$filecontent中有文件内容,$filepath中有要使用的文件名(具有适当的扩展名),则可以使用

file_put_contents($filename, $filecontent)

在你的循环中这样做,你就完了。

有关file_put_contents的详细信息,请参阅其php手册页。

我推荐一种面向对象的方法来解决这一切:

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对象数组的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
}