Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/259.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/xpath/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 将XPath结果转换为字符串_Php_Xpath_Simplexml - Fatal编程技术网

Php 将XPath结果转换为字符串

Php 将XPath结果转换为字符串,php,xpath,simplexml,Php,Xpath,Simplexml,我将要将XML转换为JSON,如下所述。我需要向该方法传递一个字符串,但我无法解决如何将XPath结果转换为字符串 我试图从如下格式的XML文件中提取特定父元素[name=bar]的所有子元素: <items> <item name="foo"> <element>1</element> <element> <child>

我将要将XML转换为JSON,如下所述。我需要向该方法传递一个字符串,但我无法解决如何将XPath结果转换为字符串

我试图从如下格式的XML文件中提取特定父元素
[name=bar]
的所有子元素:

    <items>
        <item name="foo">
            <element>1</element>
            <element>
                <child>c1</child>        
            </element>
            <element>2</element>
        </item>
        <item name="bar">
            <element>1</element>
            <element>
                <child>c1</child>        
            </element>
            <element>2</element>
        </item>
    </items>
我想将结果转换为字符串:

        <item name="bar">
            <element>1</element>
            <element>
                <child>c1</child>        
            </element>
            <element>2</element>
        </item>

1.
c1
2.

任何帮助都将不胜感激。

您可以循环使用XPath结果,然后使用将节点保存为字符串形式的变量:

$str = ''; // initializing empty string to append to 
$item = $xmlfile->xpath('//item[@name="bar"]');
while(list(,$node) = each($item)) { // getting each node
    $str .= $node->asXML(); // save it to $str
}    
echo $str;

也许您可以使用
内爆()功能你好,谢谢。有趣的是,我注意到我以前做过,但是没有看到结果,所以我看不到!!lol@beingalex:不客气。只是一个旁注:您可以始终使用
标题('Content-Type:text/plain')
仅显示文本内容而不显示任何格式。干杯:)
$str = ''; // initializing empty string to append to 
$item = $xmlfile->xpath('//item[@name="bar"]');
while(list(,$node) = each($item)) { // getting each node
    $str .= $node->asXML(); // save it to $str
}    
echo $str;