如何在codeigniter中生成xml

时间:2022-10-06 13:45:10

I am trying to generate xml from database query.

我试图从数据库查询生成XML。

Here is generated xml link: http://mydeal.ge/api/xml

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

But when I try to parse this xml, I get an error: http://wallsparade.com/test.php.

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

My code is:

我的代码是:

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;

    }

What is problem?

有什么问题?

4 个解决方案

#1


3  

Looks like you are developing an API. Why don't you use the RESTServer plugin for CodeIgniter?

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

It's all handled for you and you don't have to worry about the format. You can choose to output in JSON or XML.

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

Plugin developed by Phil: https://github.com/philsturgeon/codeigniter-restserver

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

#2


1  

Your XML document have to start with:

您的XML文档必须以:

<?xml version="1.0"?>

no white symbols no "spaces" no "enters". Your document starts with line-break as the error message says:

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

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

and delete spaces from this line:

并从此行中删除空格:

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

#3


1  

I believe the most practical, logical and error free way to generate an XML is to create a DOMDocument as suggested by Eineki in this answer, allowing the xmltree to be searched through an xpath query.

我相信生成XML的最实用,逻辑和无错误的方法是在这个答案中创建一个由Eineki建议的DOMDocument,允许通过xpath查询搜索xmltree。

With this said, some years ago Dan Simmons created a single MY_xml_helper.php that you can just copy to your application/helpers folder directly. Here's the entire code without comments:

有了这个说,几年前Dan Simmons创建了一个单独的MY_xml_helper.php,你可以直接复制到你的应用程序/帮助文件夹。这是没有注释的整个代码:

<?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;
		}
	}
}

Notice that you set the encoding like this: new DOMDocument('1.0', 'UTF-8');. Here's an example:

请注意,您可以像这样设置编码: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);

Would simply output:

只需输出:

<?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>

The xml_print either echos or returns the $xml->saveXML().

xml_print要么回声,要么返回$ xml-> saveXML()。

Notice: you can still use the one and only function from the default XML helper from CodeIgniter: xml_convert("<title>'Tom' & \"Jerry\"") which just outputs: &lt;title&gt;&apos;Tom&apos; &amp; &quot;Jerry&quot;.

注意:您仍然可以使用来自CodeIgniter的默认XML帮助程序中的唯一函数:xml_convert(“

'Tom'和\”Jerry \“”),它只输出:< title>'Tom'。 &安培; "杰里" ;.</p>

#4


0  

You shouldn't write XML through string concatenation when you have built-in library such as SimpleXMLElement available.

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

Try to change your code to this. I couldn't test it myself but it should work as expected:

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

<?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();
}

#1


3  

Looks like you are developing an API. Why don't you use the RESTServer plugin for CodeIgniter?

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

It's all handled for you and you don't have to worry about the format. You can choose to output in JSON or XML.

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

Plugin developed by Phil: https://github.com/philsturgeon/codeigniter-restserver

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

#2


1  

Your XML document have to start with:

您的XML文档必须以:

<?xml version="1.0"?>

no white symbols no "spaces" no "enters". Your document starts with line-break as the error message says:

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

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

and delete spaces from this line:

并从此行中删除空格:

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

#3


1  

I believe the most practical, logical and error free way to generate an XML is to create a DOMDocument as suggested by Eineki in this answer, allowing the xmltree to be searched through an xpath query.

我相信生成XML的最实用,逻辑和无错误的方法是在这个答案中创建一个由Eineki建议的DOMDocument,允许通过xpath查询搜索xmltree。

With this said, some years ago Dan Simmons created a single MY_xml_helper.php that you can just copy to your application/helpers folder directly. Here's the entire code without comments:

有了这个说,几年前Dan Simmons创建了一个单独的MY_xml_helper.php,你可以直接复制到你的应用程序/帮助文件夹。这是没有注释的整个代码:

<?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;
		}
	}
}

Notice that you set the encoding like this: new DOMDocument('1.0', 'UTF-8');. Here's an example:

请注意,您可以像这样设置编码: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);

Would simply output:

只需输出:

<?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>

The xml_print either echos or returns the $xml->saveXML().

xml_print要么回声,要么返回$ xml-> saveXML()。

Notice: you can still use the one and only function from the default XML helper from CodeIgniter: xml_convert("<title>'Tom' & \"Jerry\"") which just outputs: &lt;title&gt;&apos;Tom&apos; &amp; &quot;Jerry&quot;.

注意:您仍然可以使用来自CodeIgniter的默认XML帮助程序中的唯一函数:xml_convert(“

'Tom'和\”Jerry \“”),它只输出:< title>'Tom'。 &安培; "杰里" ;.</p>

#4


0  

You shouldn't write XML through string concatenation when you have built-in library such as SimpleXMLElement available.

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

Try to change your code to this. I couldn't test it myself but it should work as expected:

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

<?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();
}