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:password@myserver.blabla/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;
?>
jskidd3
  • 4,609
  • 15
  • 63
  • 127

1 Answers1

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.

Community
  • 1
  • 1
Tamás Pap
  • 17,777
  • 15
  • 70
  • 102