【问题标题】:How to generate xml in codeigniter如何在codeigniter中生成xml
【发布时间】:2013-07-25 03:01:57
【问题描述】:

我正在尝试从数据库查询中生成 xml。

这里是生成的xml链接:http://mydeal.ge/api/xml

但是当我尝试解析这个 xml 时,我得到一个错误:http://wallsparade.com/test.php

我的代码是:

public function xml()
    {
        $res = $this->db->query('custom query');
        if($res->num_rows() > 0)
        {$output =  '<?xml version="1.0"?>'. "\n";
            $output .= "<deals>";
            foreach($res->result() as $item)
        {
            $output .= "<sale id = '".$item->id."'>";
            $output .= "<link>".$item->link."</link>";
            $output .= "<title>".urlencode($item->title)."</title>";
            $output .= "<image>".$item->image."</image>";
            $output .= "<text>".urlencode($item->text)."</text>";
            $output .= "<time>".$item->time."</time>";
            $output .= "<price>".$item->price."</price>";
            $output .= "<parcent>".$item->parcent."</parcent>";
            $output .= "</sale>";
        }
        $output .= '</deals>';
        }

        echo $output;

    }

什么问题?

【问题讨论】:

    标签: php xml codeigniter


    【解决方案1】:

    我认为生成 XML 的最实用、合乎逻辑且无错误的方法是创建 DOMDocument as suggested by Eineki in this answer,允许通过 xpath 查询搜索 xmltree。

    话虽如此,几年前Dan Simmons created a single MY_xml_helper.php 可以直接复制到application/helpers 文件夹中。这是没有 cmets 的完整代码:

    <?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
    
    if ( ! function_exists('xml_dom'))
    {
    	function xml_dom()
    	{
    		return new DOMDocument('1.0', 'UTF-8');
    	}
    }
    
    if ( ! function_exists('xml_add_child'))
    {
    	function xml_add_child($parent, $name, $value = NULL, $cdata = FALSE)
    	{
    		if($parent->ownerDocument != "")
    		{
    			$dom = $parent->ownerDocument;			
    		}
    		else
    		{
    			$dom = $parent;
    		}
    		
    		$child = $dom->createElement($name);		
    		$parent->appendChild($child);
    		
    		if($value != NULL)
    		{
    			if ($cdata)
    			{
    				$child->appendChild($dom->createCdataSection($value));
    			}
    			else
    			{
    				$child->appendChild($dom->createTextNode($value));
    			}
    		}
    		
    		return $child;		
    	}
    }
    
    
    if ( ! function_exists('xml_add_attribute'))
    {
    	function xml_add_attribute($node, $name, $value = NULL)
    	{
    		$dom = $node->ownerDocument;			
    		
    		$attribute = $dom->createAttribute($name);
    		$node->appendChild($attribute);
    		
    		if($value != NULL)
    		{
    			$attribute_value = $dom->createTextNode($value);
    			$attribute->appendChild($attribute_value);
    		}
    		
    		return $node;
    	}
    }
    
    
    if ( ! function_exists('xml_print'))
    {
    	function xml_print($dom, $return = FALSE)
    	{
    		$dom->formatOutput = TRUE;
    		$xml = $dom->saveXML();
    		if ($return)
    		{
    			return $xml;
    		}
    		else
    		{
    			echo $xml;
    		}
    	}
    }

    请注意,您将编码设置为:new DOMDocument('1.0', 'UTF-8');。这是一个例子:

    $this->load->helper('xml');
    $dom = xml_dom();
    $book = xml_add_child($dom, 'book');
    xml_add_child($book, 'title', 'Hyperion');
    $author = xml_add_child($book, 'author', 'Dan Simmons');        
    xml_add_attribute($author, 'birthdate', '1948-04-04');
    xml_add_child($author, 'name', 'Dan Simmons');
    xml_add_child($author, 'info', 'The man that wrote MY_xml_helper'); 
    xml_print($dom);
    

    只会输出:

    <?xml version="1.0" encoding="UTF-8"?>
    <book>
        <title>Hyperion</title>
        <author birthdate="1948-04-04">
         <name>Dan Simmons</name>
         <info>The man that wrote MY_xml_helper</info>
        </author>
    </book>
    

    xml_print 要么echos 要么返回$xml-&gt;saveXML()

    注意:您仍然可以使用 default XML helper from CodeIgniter 中的唯一一个函数:xml_convert("&lt;title&gt;'Tom' &amp; \"Jerry\""),它只输出:&amp;lt;title&amp;gt;&amp;apos;Tom&amp;apos; &amp;amp; &amp;quot;Jerry&amp;quot;

    【讨论】:

      【解决方案2】:

      看起来您正在开发 API。为什么不使用 CodeIgniter 的 RESTServer 插件?

      一切都为您处理,您不必担心格式。您可以选择以 JSON 或 XML 格式输出。

      Phil 开发的插件:https://github.com/philsturgeon/codeigniter-restserver

      【讨论】:

        【解决方案3】:

        当您有内置库(例如SimpleXMLElement)可用时,您不应该通过字符串连接来编写 XML。

        尝试将您的代码更改为此。我无法自己测试它,但它应该可以按预期工作:

        <?php
        public function xml()
        {
            $res = $this->db->query('custom query');
            if ($res->num_rows() > 0) {
                $sxe   = new SimpleXMLElement();
                $deals = $sxe->addChild('deals');
        
                foreach($res->result() as $item) {
                    $sale = $deals->addChild('sale');
                    $sale->addAttribute('id', $item->id);
                    $sale->addChild('link', $item->link);
                    $sale->addChild('title', urlencode($item->title));
                    $sale->addChild('image', $item->image);
                    $sale->addChild('text', urlencode($item->text));
                    $sale->addChild('time', $item->time);
                    $sale->addChild('price', $item->price);
                    $sale->addChild('parcent', $item->parcent);
                }
            }
        
            echo $sxe->saveXML();
        }
        

        【讨论】:

          【解决方案4】:

          您的 XML 文档必须以:

          <?xml version="1.0"?>
          

          没有白色符号没有“空格”没有“输入”。如错误消息所示,您的文档以换行符开头:

          Warning: simplexml_load_file() [function.simplexml-load-file]: http://mydeal.ge/api/xml:2: parser error : XML declaration allowed only at the start of the document in /home1/stinky/public_html/test.php on line 2
          

          并从该行删除空格:

          $output .= "<sale id = '".$item->id."'>";
          $output .= "<sale id='".$item->id."'>";
          

          【讨论】:

          • 试试这个“echo trim($output);”
          猜你喜欢
          • 1970-01-01
          • 2015-10-29
          • 1970-01-01
          • 2012-10-24
          • 1970-01-01
          • 2023-03-12
          • 2011-12-22
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多