0

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
4

1 回答 1

5

我会说最可能的答案是您需要传递 URL 值urlencode()- 特别是 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);
于 2012-01-19T10:57:08.540 回答