【问题标题】:Acessing The Return Array访问返回数组
【发布时间】:2012-05-08 22:04:17
【问题描述】:

编辑:

<?php
    $file= 'fbplus.jpg';

    $args = array(
       'message' => $album_message,
    );
    $args[basename($file)] = '@' . realpath($file);
    $ch = curl_init();
    $url = $graph_url;
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $args);
    $data = curl_exec($ch);
    //returns the photo id
    print_r(json_decode($data,true));


    echo "$data['id'] "; //wont work
        echo "$data[id] "; //wont work


?>

这是我成功上传照片后的回报。

数组([id] => 112235735579158 [post_id] => 100003781972892_112203478915717)

【问题讨论】:

  • 那不是副手吗?大批?应该是 $data['id'] 而不是 $data[id]
  • 如果那是数组,那么 $data['id'] 应该可以工作。另外,请使用长的开放标签。以后当你被困在没有启用短开放标签的服务器上时,你可能会后悔。
  • @Smamatti,是的,从语法上讲,id 应该用引号引起来,但这不是造成问题的原因。
  • 还有等号 = $data['id']; ?>
  • @jcubic, short_open_tag (&lt;? ?&gt;) 已弃用,并在 PHP 5.3.0 中被删除

标签: php arrays curl return


【解决方案1】:

curl_exec() 返回一个字符串(网页的内容),而不是 Array。所以你不能做$data['id'] 因为$data 是一个字符串而不是一个数组。

您要发帖的网址是什么?它的确切输出是什么?

编辑:看起来 url 返回 JSON。在这种情况下:

<?php
    $file= 'fbplus.jpg';

    $args = array(
       'message' => $album_message,
    );
    $args[basename($file)] = '@' . realpath($file);
    $ch = curl_init();
    $url = $graph_url;
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $args);
    $data = curl_exec($ch);
    //returns the photo id

    $data = json_decode($data,true);

    echo $data['id'];
?>

【讨论】:

  • 我用过这个 print_r(json_decode($data,true));输出是数组([id] => 112265748909490 [post_id] => 100003781972892_112203478915717)。那为什么是数组呢?
  • 啊,这是一个数组,因为您使用的是 json_decode(),您在原始问题中没有提到。
  • @RoxyGutera,我已经用有效的代码编辑了我的答案。当您在 print_r() 中执行 json_decode() 时,您并没有将其分配给 $data 变量!
  • 输出是 {(一个花括号)。发生了什么事?
  • 很抱歉我忘记删除 print_r。感谢 NADH,它起作用了
【解决方案2】:

您是否在访问 Facebook Graph API?

如果是这样,请使用:

$data = json_decode($data);

你可以通过$data-&gt;id访问它

【讨论】:

  • 这是我的第一种方法,但 $data->id 仍然为 NULL。是的图形 api 和 $data = json_decode($data);已经在我的代码中了。但我仍然无法访问数组
  • @Roxy,默认情况下,json_decode() 返回一个对象。如果你想得到一个数组,试试json_decode($data, true)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-09-25
  • 2021-03-21
  • 1970-01-01
  • 2010-12-12
  • 2010-11-30
  • 2011-04-08
  • 2011-02-21
相关资源
最近更新 更多