【问题标题】:Reading JSON in PHP with only the libraries in Wordpress仅使用 Wordpress 中的库在 PHP 中读取 JSON
【发布时间】:2013-03-18 07:13:48
【问题描述】:

我想读取进入安装了足够 PHP 以运行 WordPress 的服务器的 JSON 数据。我可以创建新的 .php 文件,但我没有管理员权限来添加任何不存在的库。

在这种情况下,从 http 请求中获取和解析 JSON 数据的最简单方法是什么?

【问题讨论】:

  • 你没有json_decode
  • 这就是答案的一半。它前面的一半原来是: $json_data = file_get_contents("php://input");

标签: php json wordpress


【解决方案1】:

感谢大家的指点,但我正在寻找的答案要简单得多。必要的两行代码原来是:

$json_data = file_get_contents("php://input");
$json_data = json_decode($json_data, true);

第一行:获取命中页面的 json 数据。 第二行:将其解析为适当的哈希。

【讨论】:

    【解决方案2】:

    如果您在 WordPress 的上下文中执行此操作,则应使用内置的 HTTP 帮助函数 (http://codex.wordpress.org/HTTP_API)。它们比 curl 更简单。示例:

    $response = wp_remote_get( $url );
    if( is_wp_error( $response ) ) {
       $error_message = $response->get_error_message();
       echo "Something went wrong: $error_message";
    } else {
       echo 'Response:<pre>';
       print_r( $response );
       echo '</pre>';
    }
    

    上面将返回如下内容:

    Array
    (
        [headers] => Array
            (
                [date] => Thu, 30 Sep 2010 15:16:36 GMT
                [server] => Apache
                [x-powered-by] => PHP/5.3.3
                [x-server] => 10.90.6.243
                [expires] => Thu, 30 Sep 2010 03:16:36 GMT
                [cache-control] => Array
                    (
                        [0] => no-store, no-cache, must-revalidate
                        [1] => post-check=0, pre-check=0
                    )
    
                [vary] => Accept-Encoding
                [content-length] => 1641
                [connection] => close
                [content-type] => application/php
            )
        [body] => {"a":1,"b":2,"c":3,"d":4,"e":5}
        [response] => Array
            (
                [code] => 200
                [message] => OK
            )
    
        [cookies] => Array
            (
            )
    
    )
    

    然后可以使用json_decode()将json变成数组:http://www.php.net/manual/en/function.json-decode.php

    【讨论】:

      【解决方案3】:

      使用 cURL 和 json_decode,您可以这样做。如果您正在运行 Wordpress,则很有可能这些都是可用的。

      $session = curl_init('http://domain.com/'); // HTTP URL to the json resource you're requesting
      curl_setopt($session, CURLOPT_FOLLOWLOCATION, TRUE);
      curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
      $json = json_decode(curl_exec($session));
      curl_close($session);
      echo $json;
      

      【讨论】:

      • $json = json_decode(curl_exec($session), true); 更好,因为它避免了对象和数组的混合。
      猜你喜欢
      • 1970-01-01
      • 2016-08-12
      • 1970-01-01
      • 1970-01-01
      • 2011-03-03
      • 1970-01-01
      • 2013-10-01
      相关资源
      最近更新 更多