【问题标题】:jQuery $.ajax() to PHP CURLjQuery $.ajax() 到 PHP CURL
【发布时间】:2012-10-26 11:40:17
【问题描述】:

我希望将以下内容翻译成 PHP CURL。

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

我特别有兴趣弄清楚我必须如何更改以下内容才能将 dataType 设置为 xml。以下代码不起作用:

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

谢谢!

【问题讨论】:

  • "内容类型:应用程序/xml;charset=utf-8",
  • jQuery 的 ajax 函数使用 dataType 参数来解析结果。你希望 curl 做什么?
  • 查看这里了解各种 MIME 类型:en.wikipedia.org/wiki/Internet_media_type
  • php parser xml with curl的可能重复
  • 谢谢。这消除了我对正在使用的 API 文档的误解。我正在将一组 jQuery 函数移植到 PHP 类中,但无法弄清楚为什么在 $.ajax() 指定“dataType:xml”时响应不断返回 HTML 表。我现在看到 jQuery 只是将 HTML 解析为 XML。谢谢大家!

标签: php jquery ajax curl


【解决方案1】:

使用 phery,您可以通过一种非常简单的方式(http://phery-php-ajax.net/)来实现,过去 2 年我一直在改进和使用我的库:

// 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();

然后使用 ajax 调用创建一个函数以使其可重用:

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

【讨论】:

    猜你喜欢
    • 2017-05-03
    • 1970-01-01
    • 2017-11-02
    • 1970-01-01
    • 2016-12-02
    • 2017-12-25
    • 2011-03-07
    • 1970-01-01
    • 2018-03-11
    相关资源
    最近更新 更多