【问题标题】:Not able to access the JSON string outside of the PHP function?无法访问 PHP 函数之外的 JSON 字符串?
【发布时间】:2015-08-29 02:12:49
【问题描述】:

我正在一个名为 curl_pair($json_pair_filename) 的 PHP 函数中卷曲 JSON 字符串。 var_dump 正确显示函数内的数据,因此数据存在于函数内,但我无法访问 PHP 函数之外的 JSON 字符串。我应该改变什么?

    if(curl_exec($ch) === false)
    { // Curl error:
        //echo '<a target="_blank" href="http://curl.haxx.se/libcurl/c/libcurl-errors.html">' . curl_error($ch) . "</a>";
        include( DOMAIN_PATH . "tickers/form_curl_error.php");
        $my_data = "something went wrong...";
    }
    else // fetch the data
    {
        $my_data = curl_multi_getcontent ( $ch );
        //var_dump($my_data);   // is ok shows json string
        curl_close( $ch );
    }
    return json_encode($my_data);
}
curl_pair($json_pair_filename); // no errors

echo($my_data); // just a white screen, no data, no nothing.

【问题讨论】:

    标签: php json function scope


    【解决方案1】:

    我认为您需要捕获函数的输出,或者将函数调用嵌套在 echo 中。我不是 PHP 开发人员,但在大多数编程语言中,函数内部声明的变量是函数私有的,因此 $my_data 不存在外部。但是你从你的函数中返回它,所以

    $result_data = curl_pair($json_pair_filename);
    echo($result_data);
    

    应该可以。

    【讨论】:

      【解决方案2】:

      请尝试执行以下代码sn-p。

      在上面的代码 sn-p 中,$my_data 变量的作用域在设置它的函数内。 要使其在函数外部可访问,您需要在调用该函数的位置返回值。

       if(curl_exec($ch) === false)
          { // Curl error:
              //echo '<a target="_blank" href="http://curl.haxx.se/libcurl/c/libcurl-errors.html">' . curl_error($ch) . "</a>";
              include( DOMAIN_PATH . "tickers/form_curl_error.php");
              $my_data = "something went wrong...";
          }
          else // fetch the data
          {
              $my_data = curl_multi_getcontent ( $ch );
              //var_dump($my_data);   // is ok shows json string
              curl_close( $ch );
          }
          return json_encode($my_data);
      }
      $my_data=curl_pair($json_pair_filename); // no errors
      
      echo($my_data); // just a white screen, no data, no nothing.
      

      【讨论】:

      • 谢谢鲁宾你是对的,这是变量范围的问题。感谢您的回复。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-08-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-15
      • 2021-11-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多