2016-05-31 54 views
1

我在http://www.domain.com:10001/api/Data.cgi?Scope=SystemCURL与港口和其他参数的URL,JSON解析

该URL格式的URL是一个JSON转储,我需要解析。我如何访问它?我之前使用过get_file_contents,这就是为什么我要为此付出努力 - 第一次在URL上使用端口。如果我可以抓住JSON并将其放入file.txt中,然后解析该文件,那将是最好的。

<?php 
$cURL = curl_init('http://81.1.1.1'); 
curl_setopt($cURL, CURLOPT_PORT, 10001); 
curl_setopt($cURL, CURLOPT_RETURNTRANSFER, true); 

$fp = fopen("example_homepage.txt", "w"); 
curl_setopt($cURL, CURLOPT_FILE, $fp); 
curl_setopt($cURL, CURLOPT_HEADER, 0); 
curl_exec($cURL); 
curl_close($cURL); 
fclose($fp); 
?> 

我不确定如何正确添加网址的其余部分。

+0

你真的问了两个问题,第一个如何用CURL获取文件内容,然后下一步如何解析JSON,对吧? 使用file_get_contents获取内容并使用json_decode解析它会更容易。 –

回答

2

如果您不需要使用卷曲,这可能是更容易的file_get_contents。

// Retrieve file 
$data = file_get_contents("http://81.1.1.1:10001/page_url.json?query_parameters=values"); 

// Echo retrieved file 
echo $data; 

// Decode JSON 
$decoded = json_decode($data); 

// Dump decoded data 
var_dump($decoded); 
+0

hi @Ross - 是否可以在带有端口的URL上使用'file_get_contents'?因为我没有得到任何回应......所以也许是我从这个问题获取信息的服务器?我怎么能证实这一点? – sixli

+1

可以使用带有file_get_contents的端口号。打开错误报告以查看是否有任何错误,确保没有防火墙规则阻止请求。 – drew010

+0

谢谢@ drew010 - 帮助 – sixli

0

试试这个:

function curl($url) { 

      $options = Array(
       CURLOPT_RETURNTRANSFER => TRUE, 
       CURLOPT_FOLLOWLOCATION => TRUE, 
       CURLOPT_AUTOREFERER => TRUE 

, 
      CURLOPT_TIMEOUT => 120, 
      CURLOPT_MAXREDIRS => 10, 
      CURLOPT_USERAGENT => "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1a2pre) Gecko/2008073000 Shredder/3.0a2pre ThunderBrowse/3.2.1.8", 
      CURLOPT_URL => $url, 

     ); 

     $ch = curl_init(); // Initialising cURL 

     curl_setopt_array($ch, $options); 

     $data = curl_exec($ch); 

     curl_close($ch);  

     return $data; 
    } 

    $scraped_page = curl($link); 
+0

所以我的代码现在看起来像这样 - https://codeshare.io/lk9CR但仍然无法工作......任何想法? – sixli