PHP - 如何使用 get 或 post 方法抓取外部 url 并从中解析 json 数据



我有一台运行ZF2的服务器,我有另一台使用PHP的客户端,现在我需要从客户端通过get或post方法读取json输出。

如何抓取外部链接表单客户端并解析 JSON 数据以读取"result"=> $msg 的值?

客户: http://www.other-end-user.com/view:

<?php
$customerid = $_GET['id'];
$id = substr('3' . rand(0,9999), 0-$length);
$default = "https://toogle.com?id={$id}";
$b = "<a href={$default} id={$customerid}button class={$customerid}button><img src="http://toogle.com/button.png" /></a>";
#curl "http://www.external-analytics-site.com/ajax/json" | grep result
$live = true
if ($live){
  echo $b;
} else {
  echo "Live query failed";    
}

?>

服务器 (ZF2): http://www.external-analytics-site.com/ajax/json:

class AjaxController extends AbstractActionController {
    public function jsonAction(){
      $response = $this->getResponse();
      $msg = true;        
      $json = array(
        'result' => $msg,
        'module' => 'ajax',
        'data' => "test"
      );
      $response->setContent(Json::encode($json));
      return $response;            
      exit;
    }
}

您可以使用file-get-content()通过 GET 从服务器读取

您可以使用json_decode来解析结果

您可以使用

file_get_content来获取json数据..但是如果您也需要页面内容..

 function crawl_page($url, $depth = 5)
{
    $saved = array();
    if (isset($saved[$url]) || $depth === 0) {
        return;
    }
    $saved[$url] = true;
    $dom = new DOMDocument('1.0');
    @$dom->loadHTMLFile($url);
    $anchors = $dom->getElementsByTagName('a');
    foreach ($anchors as $element) {
        $href = $element->getAttribute('href');
        if (0 !== strpos($href, 'http')) {
            $path = '/' . ltrim($href, '/');
            if (extension_loaded('http')) {
                $href = http_build_url($url, array('path' => $path));
            } else {
                $parts = parse_url($url);
                $href = $parts['scheme'] . '://';
                if (isset($parts['user']) && isset($parts['pass'])) {
                    $href .= $parts['user'] . ':' . $parts['pass'] . '@';
                }
                $href .= $parts['host'];
                if (isset($parts['port'])) {
                    $href .= ':' . $parts['port'];
                }
                $href .= $path;
            }
        }
        $this->crawl_page($href, $depth - 1);
    }
    echo "URL:",$url,PHP_EOL,"CONTENT:",PHP_EOL,$dom->saveHTML(),PHP_EOL,PHP_EOL;
}

最新更新