0

The code below sends XML via CURL using POST with a http header of text/xml. The server responds by echoing $ch_result. I am making a call to this file via AJAX as the content of the returned XML file will need to be displayed on the client-side. Is there anyway I can get this XML file into an array so I can use json_encode and have it return like that? I need this content to be easy to manipulate using JavaScript as the XML file returned is large... so an array might be best?

Thanks!

<?php
  $xml_builder = '
                  MY XML POSTED TO SERVER GOES HERE';
  $ch = curl_init('http://username:[email protected]/api');
  curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml'));
  curl_setopt($ch, CURLOPT_HEADER, 0);
  curl_setopt($ch, CURLOPT_POST, 1);
  curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_builder);
  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
  curl_setopt($ch, CURLOPT_REFERER, 'http://www.mydomain.co.uk');
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  $ch_result = curl_exec($ch);
  curl_close($ch);

  echo $ch_result;
?>
2

1 Answer 1

3

You can parse the XML on server side, but also on client side.

On server side:

Simple and dirty way:

<?php
  $a = json_decode(json_encode((array) simplexml_load_string($s)),1);
?>

however, please read this article:

http://gaarf.info/2009/08/13/xml-string-to-php-array/

On client side:

If you are using jQuery you can set dataType to xml, and can parse the xml on client side with jQuery:

How to parse XML using jQuery?

To parse xml using jquery you must echo: htmlentities($ch_result) so that the XML is echoed with the tags etc.

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

1 Comment

Great, thanks! I think I'll use .parseXML(), thanks for bringing my attention to it! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.