0

I am going to be converting XML to JSON as described here. I need to pass that method a string and I can't work out how to convert my XPath result to a string.

I am trying to extract all children of a specific parent element, [name=bar], from an XML file that is formatted like this:

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

I can access the node I want:

 $xmlfile = simplexml_load_file('xmlfile.xml'); $item = $productsXml->xpath('//item[@name="bar"]'); // Returns an array 

I would like to convert the result to a string:

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

Any help would be appreciated.

1

1 Answer 1

1

You can loop through the XPath results and then use asXML() to save the node to a variable as a string:

$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; 

Demo!

Sign up to request clarification or add additional context in comments.

2 Comments

Hi thank you for that. Funnily enough I noticed that I had done that before but didn't htmlentities the result so I couldn't see it!! lol
@beingalex: You're welcome. Just a sidenote: you can always use header('Content-Type: text/plain'); to just display the text content without any formatting. Cheers :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.