file_get_contents不适用于使用批处理请求从facebook获取数据


file_get_contents not working for fetching data from facebook using batch requests

file_get_contents不适用于使用批处理请求从facebook获取fata。我使用以下代码:

  $url='https://graph.facebook.com/?batch=[{ "method": "POST", "relative_url":"method/fql.query?query=SELECT+first_name+from+user+where+uid=12345678"}]&  access_token=xxxxxxx&method=post';
 echo  $post = file_get_contents($url,true);
it produces 
    Warning: file_get_contents(graph.facebook.com/?batch=[{ "method": "POST", "relative_url": "method/fql.query?query=SELECT+first_name+from+user+where+uid=12345"}]&access_to‌ ​ken=xxxx&method=post): failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request in /home/user/workspace/fslo/test.php on line 9

我认为最有可能的答案是,您需要通过urlencode()传递URL值,尤其是JSON字符串。

此外,您应该对数据进行POST处理。

试试这个代码:

注意:我认为你是从几个变量构建URL的。如果您用实际代码编辑问题,我将使用该代码提供解决方案

<?php
  $baseURL = 'https://graph.facebook.com/';
  $requestFields = array (
    'batch' => '[{"method":"POST","relative_url":"method/fql.query?query=SELECT+first_name+from+user+where+uid=12345678"}]',
    'access_to‌ken' => 'whatever'
  );
  $requestBody = http_build_query($requestFields);
  $opts = array(
    'http'=>array(
      'method' => 'POST',
      'header' => "Content-Type: application/x-www-form-urlencoded'r'n"
                . "Content-Length: ".strlen($requestBody)."'r'n"
                . "Connection: close'r'n",
      'content' => $requestBody
    )
  );
  $context = stream_context_create($opts);
  $result = file_get_contents($baseURL, FALSE, $context);

如今,一种"更标准"的方法是使用cURL:

<?php
  $baseURL = 'https://graph.facebook.com/';
  $requestFields = array (
    'batch' => '[{"method":"POST","relative_url":"method/fql.query?query=SELECT+first_name+from+user+where+uid=12345678"}]',
    'access_to‌ken' => 'whatever'
  );
  $requestBody = http_build_query($requestFields);
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $baseURL);
  curl_setopt($ch, CURLOPT_POST, TRUE);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
  curl_setopt($ch, CURLOPT_POSTFIELDS, $requestBody);
  curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/x-www-form-urlencoded',
    'Content-Length: '.strlen($requestBody),
    'Connection: close'
  ));
  $post = curl_exec($ch);