使用PHP'访问处理指令;s SimpleXML

使用PHP'访问处理指令;s SimpleXML,php,xml,simplexml,processing-instruction,Php,Xml,Simplexml,Processing Instruction,非常简单——有没有任何方法可以使用SimpleXML访问处理指令节点的数据?我知道SimpleXML很简单;因此,它有许多局限性,主要用于混合内容节点 例如: Test.xml <test> <node> <?php /* processing instructions */ ?> </node> </test> $test = simplexml_load_file('Test.xml'); var_

非常简单——有没有任何方法可以使用SimpleXML访问处理指令节点的数据?我知道SimpleXML很简单;因此,它有许多局限性,主要用于混合内容节点

例如:

Test.xml

<test>
    <node>
        <?php /* processing instructions */ ?>
    </node>
</test>
$test = simplexml_load_file('Test.xml');
var_dump($test->node->php); // dumps as a SimpleXMLElement, so it's sorta found,
                            // however string casting and explicitly calling
                            // __toString() yields an empty string

那么这仅仅是SimpleXML的简单性造成的技术限制,还是有办法?如果有必要,我将转换到SAX或DOM,但是SimpleXML会很好。

问题是

?php?>被认为是一个标签。。。所以它被解析成一个大标记元素。您需要执行以下操作:

$xml = file_get_contents('myxmlfile.xml');
$xml = str_replace('<?php', '<![CDATA[ <?php', $xml);
$xml = str_replace('?>', '?> ]]>', $xml);
$xml = simplexml_load_string($xml, "SimpleXMLElement", LIBXML_NOCDATA);
$xml=file\u get\u contents('myxmlfile.xml');
$xml=str_replace(“”,“?>]]]>',$xml);
$xml=simplexml\u load\u字符串($xml,“simplexmlement”,LIBXML\u NOCDATA);

我不完全确定这是否可行,但我认为会的。测试它…

您在此处访问的SimpleXML节点:

$test->node->php
不知何故,这就是处理指令。但不知何故,情况并非如此。只要没有其他同名元素,就可以更改处理指令的内容:

$test->node->php = 'Yes Sir, I can boogie. ';

$test->asXML('php://output');
这将创建以下输出:

<?xml version="1.0"?>
<test>
    <node>
        <?php Yes Sir, I can boogie. ?>
    </node>
</test>
啊,我明白了,;哎呀--我想我还是回到DOM/SAX上来吧。
$doc   = dom_import_simplexml($test)->ownerDocument;
$xpath = new DOMXPath($doc);

# prints "/* processing instructions */ ", the value of the first PI:

echo $xpath->evaluate('string(//processing-instruction("php")[1])');