【问题标题】:Can't able to get json data from URL in PHP无法从 PHP 中的 URL 获取 json 数据
【发布时间】:2016-08-25 21:12:00
【问题描述】:

需要:

我需要从 URL 获取 json 数据

问题:

返回空值

试试:

我尝试了 CURL 和 file_get_contents 方法。但都没有给出结果

示例代码:

<?php
ini_set("allow_url_fopen", 1);
$url="http://techpaisa.com/chart/wipro/atr/?xhr";
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL,$url);
$result=curl_exec($ch);
curl_close($ch);
$r=json_decode($result);
print_r($r);
?>

此代码返回空。我刚试过,复制json并放在我自己的网站上。然后我尝试了,我得到了结果。

我从“http://techpaisa.com/chart/wipro/atr/?xhr”得到以下标题:

Server: nginx/0.7.65
Content-Type: application/json
Keep-Alive: timeout=20
Vary: Accept-Encoding
Transfer-Encoding: chunked
Date: Thu, 25 Aug 2016 20:59:46 GMT
X-Varnish: 462939608 462936037
Age: 3494
Via: 1.1 varnish
Connection: keep-alive

我自己的页面代码和标题:(跳过了一些 Json)

<?php
header('Content-type: application/json');
echo "{'content': 'Date,Price,ATR#1995/02/01,37.0,0.5', 'analysis_type': 'atr', 'text_analysis': 'ATR: 9.57', 'axisname': 'Price', 'analysis_type_verbose': 'Average True Range', 'image_type': 'text/csv', 'symbol': 'wipro', 'fig_title': 'WIPRO Average True Range', 'annotations': '[]', 'set_date_range': true}";
?>

标头值:

Server: Apache
X-Powered-By: PHP/5.3.29
Transfer-Encoding: chunked
Content-Type: application/json

【问题讨论】:

  • 这不是有效的 JSON。
  • 那么,我必须如何在 php 中显示 json
  • 以有效的 JSON 格式 :)

标签: php json curl


【解决方案1】:

我刚试过

var_dump(json_decode(file_get_contents($url), true));

它有效。 您的代码也应该可以工作

如果没有,这里还有其他东西在起作用。

  • 您从哪里运行该代码?也许有防火墙或其他机制允许读取它自己的网页和脚本,但不能读取外部资源。这通常是为了防止资源滥用。

  • 您是否可以阅读该信息?如果没有,那么可能是网站管理员注意到有人“抓取”数据并锁定了您当前 Web 服务器的地址。您仍然可以在家中读取该信息,只是服务器上的 PHP 代码将不再工作。

我个人赌的是原因 #1。在这种情况下,您必须向管理您的网络服务器的人提出。

【讨论】:

  • 我正在从我的直接网站 url 运行此代码,并使用 cron 作业运行该 url。我会试试你的代码
【解决方案2】:

谢谢lserni

我接受你的回答。

您的代码正在运行。但问题是,我无法从键名中获得价值。

示例:

url="http://techpaisa.com/chart/wipro/atr/?xhr";
$result=json_decode(file_get_contents($url), true);
var_dump($result->content);

它给出以下错误:

Notice: Trying to get property of non-object myfile.php

但我使用以下代码解决了这个问题:

$url="http://techpaisa.com/chart/wipro/atr/?xhr";
$data = json_decode(file_get_contents($url,true));
var_dump($data->content);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-28
    • 1970-01-01
    • 2013-07-14
    • 2016-08-06
    • 2017-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多