3

I am looking to translate the following into PHP CURL.

$.ajax({
  url:"MY_URL",
  cache: false,
  type: "POST",
  data: "",
  dataType: "xml",
  success: function(data) { 
    alert('Eureka!')
    }
});

I'm particularly interested in figuring out how I have to alter the following to get the dataType set to xml. The following code is not working:

$ch = curl_init('MY_URL');
curl_setopt($ch, CURLOPT_HEADER, 0); // get the header 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1);
curl_setopt($ch,CURLOPT_HTTPHEADER,array (
      "Content-Type: xml; charset=utf-8",
      "Expect: 100-continue",
      "Accept: xml"
     ));

Thanks!

clutterjoe
  • 61
  • 3
  • 7
  • 5
    "Content-Type: application/xml; charset=utf-8", – ninaj Nov 06 '12 at 13:48
  • 3
    The dataType parameter is used by jQuery's ajax function to *parse* the result. What do you expect curl to do ? – Denys Séguret Nov 06 '12 at 13:49
  • See here for various MIME types: http://en.wikipedia.org/wiki/Internet_media_type – Bud Damyanov Nov 06 '12 at 13:50
  • possible duplicate of [php parser xml with curl](http://stackoverflow.com/questions/6180669/php-parser-xml-with-curl) – Denys Séguret Nov 06 '12 at 13:53
  • Thanks. This cleared my misunderstanding of the documentation on the API with which I'm working. I'm porting a set of jQuery functions to a PHP class, and could not figure out why the response kept returning an HTML table when $.ajax() was specifying "dataType:xml". I see now that jQuery was just parsing the HTML as XML. Thanks everyone! – clutterjoe Nov 06 '12 at 14:25

1 Answers1

2

Using the phery, you can do it in a pretty straightforward way (in http://phery-php-ajax.net/), I've been improving and using my library for the past 2 years:

// file would be curl.php
Phery::instance()->set(array(
  'curl' => function($data){
    $ch = curl_init($data['url']);
    curl_setopt($ch, CURLOPT_HEADER, 0); // get the header 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
    curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1);
    curl_setopt($ch,CURLOPT_HTTPHEADER,array (
      "Content-Type: xml; charset=utf-8",
      "Expect: 100-continue",
      "Accept: xml"
    ));
    $data = curl_exec($ch);
    curl_close($ch);
    return PheryResponse::factory()->json(array('xml' => $data)); 
  }
))->process();

Then create a function with the ajax call to make it reusable:

/* config would be {'url':'http://'} */
function curl(url){
  return phery.remote('curl', {'url': url}, {'target': 'curl.php'}, false);
}

curl('http://somesite/data.xml').bind('phery:json', function(event, data){
  // data.xml now contains the XML data you need
}).phery('remote'); // call the remote curl function 
pocesar
  • 6,860
  • 6
  • 56
  • 88