使用CodeIgniter创建XML

时间:2012-04-28 06:05:54

标签: php xml codeigniter

我在Codeigniter中使用此代码生成XML:

public function get_cuisine()
{
    $this->load->dbutil();
    $sql = "select * from cuisine";
    $query = $this->db->query($sql);
    $config = array (
        'root'    => 'root',
        'element' => 'element',
        'newline' => "\n",
        'tab'     => "\t"
    );
    echo $this->dbutil->xml_from_result($query, $config);   
}   

但是这显示了一般的打印格式。如何将其显示为XML类型页面?

4 个答案:

答案 0 :(得分:16)

如果要直接输出文件,则需要设置XML标头:

使用Codeigniter Output class

$xml = $this->dbutil->xml_from_result($query, $config);
$this->output->set_content_type('text/xml');
$this->output->set_output($xml); 

或者您可以使用纯PHP设置headers

header('Content-type: text/xml');
echo $this->dbutil->xml_from_result($query, $config);

或者您可以使用CI download helper

$xml = $this->dbutil->xml_from_result($query, $config);
$this->load->helper('download');
force_download('myfile.xml', $xml);

或者使用file helper

将其写入文件
$xml = $this->dbutil->xml_from_result($query, $config);
$this->load->helper('file');
$file_name = '/path/to/myfile.xml';
write_file($file_name, $xml);
// Optionally redirect to the file you (hopefully) just created
redirect($file_name); 

答案 1 :(得分:2)

我也有同样的问题。我用谷歌搜索了它。找到了解决方案。它对我来说非常适合。 Click here to get the source code

只需下载并解压缩(解压缩)

然后将解压缩文件夹的application->库中的 xml_writer.php 复制到Codeigniter项目的libraries文件夹中。

同时将application->控制器中的 xml.php 复制到您的控制器文件夹

最后将解压文件夹视图中的 xml.php 复制到您的视图中并运行它。

就是这样......

答案 2 :(得分:0)

自定义解决方案:

$mysql_data = $this->db->get('products')
                    ->result_array();
$xml = '<root>';
foreach($mysql_data as $row){
  $xml .= '<item>
             <name>'.$row['title'].'</name>
             <price>'.$row['price'].'</price>
             <image>'.$row['pic'].'</image>
           </item>';
}
$xml .= '</root>';
$this->output->set_content_type('text/xml');
$this->output->set_output($xml);

答案 3 :(得分:0)

对于 CodeIgniter 4,它更容易。您可以使用集成响应对象并执行以下操作:

return $this->response->setXML($xmlString);

这简化了很多,在我的例子中,我使用视图生成 XML,然后使用同样的东西输出 XML,就像:

return $this->response->setXML(view('myfeed'));