SimpleXML 插入处理指令(样式表) [英] SimpleXML insert Processing Instruction (Stylesheet)
问题描述
我想在 php
CURL
命令给我的 XML
字符串中集成一个 XSL
文件.我试过了
I want to integrate an XSL
file in an XML
string gived me by php
CURL
command.
I tryed this
$output = XML gived me by curl option;
$hotel = simplexml_load_string($output);
$hotel->addAttribute('?xml-stylesheet type="text/xsl" href="css/stile.xsl"?');
echo $hotel->asXML();
当我在浏览器上看到 XML 时执行此操作,我收到没有样式表的文件.我的错误在哪里?
Doing this when I see the XML on browser, I receive the file without the stylesheet. Where is my error?
推荐答案
SimpleXMLElement 默认情况下不允许您创建和添加处理指令 (PI) 到一个节点.但是姐妹库 DOMDocument 允许这样做.您可以通过从 SimpleXMLElement 扩展并将两者结合起来并创建一个函数来提供该功能:
A SimpleXMLElement does not allow you by default to create and add a Processing Instruction (PI) to a node. However the sister library DOMDocument allows this. You can marry the two by extending from SimpleXMLElement and create a function to provide that feature:
class MySimpleXMLElement extends SimpleXMLElement
{
public function addProcessingInstruction($target, $data = NULL) {
$node = dom_import_simplexml($this);
$pi = $node->ownerDocument->createProcessingInstruction($target, $data);
$result = $node->appendChild($pi);
return $this;
}
}
这很容易使用:
$output = '<hotel/>';
$hotel = simplexml_load_string($output, 'MySimpleXMLElement');
$hotel->addProcessingInstruction('xml-stylesheet', 'type="text/xsl" href="style.xsl"');
$hotel->asXML('php://output');
示例输出(美化):
<?xml version="1.0"?>
<hotel>
<?xml-stylesheet type="text/xsl" href="style.xsl"?>
</hotel>
另一种方法是将 XML 块插入 simplexml 元素:"PHP SimpleXML:在特定位置插入节点" 或 将 XML 插入 SimpleXMLElement".
Another way is to insert an XML chunk to a simplexml element: "PHP SimpleXML: insert node at certain position" or "Insert XML into a SimpleXMLElement".
这篇关于SimpleXML 插入处理指令(样式表)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!