【问题标题】:Get contents of web page and place in array or string获取网页内容并放入数组或字符串中
【发布时间】:2016-02-25 05:06:14
【问题描述】:

我不确定如何表达这个问题,所以我会尽可能地问。

我想知道如何抓取网页的内容并将其放入字符串或数组中,以便解析数据。

这是网页:https://campusdata.uark.edu/api/buses?callback=?&routeIds=8

网页返回如下内容:

?([{"id":25,"fleet":15,"name":"Fleet 15","description":"","zonarId":9,"gpsId":"8061088","latitude":"36.0680039","longitude":"-94.1758039","speed":0.000,"heading":89.700,"power":true,"date":"\/Date(1456339080000)\/","color":"#0090ff","routeName":"Blue","routeId":8,"distance":9999999999,"nextStop":"Garland Center","nextArrival":"8 mins"},{"id":33,"fleet":6,"name":"Fleet 6 ","description":"","zonarId":13,"gpsId":"8061090","latitude":"36.0818423","longitude":"-94.1707598","speed":0.000,"heading":181.700,"power":true,"date":"\/Date(1456339200000)\/","color":"#0090ff","routeName":"Blue","routeId":8,"distance":2.31887983012931,"nextStop":"South Creekside","nextArrival":"1 mins"}]);

我不确定解决此问题的最佳方法...通过 JQuery 进行 AJAX?也许是一个php调用?我不知道。

我已经搜索过这个,但就像我说的那样,我不知道如何准确地表达这个问题,所以我的搜索结果充其量只是零星的。 有人可以帮帮我吗?

【问题讨论】:

  • 它是 jsonp,你可以用 jquery 获取它,或者简单地将脚本标签指向 url:<script src="https://campusdata.uark.edu/api/buses?callback=console.log&routeIds=8"></script>,它会记录数据。如果您想做的不仅仅是记录它,您需要通过将 console.log 更改为您的函数名称来将其传递给需要数据的函数。
  • 'Web Crawler' 是您正在寻找的短语stackoverflow.com/questions/13029811/…

标签: javascript php jquery ajax


【解决方案1】:

看起来像一个 JSONP 调用。您可以使用 jQuery 轻松地从 API 端点获取数据。请看下面的例子:

$.ajax({
        url: "https://campusdata.uark.edu/api/buses?callback=?&routeIds=8",

        // The name of the callback parameter
        jsonp: "callback",

        // Tell jQuery we're expecting JSONP
        dataType: "jsonp",

        data: {},

        // Work with the response
        success: function( response ) {
            console.log( response ); // server response
        }
    });

这是一个带有工作示例的jsfiddle。 在尝试此操作之前,请确保在页面中包含 jquery。

【讨论】:

  • 你应该把回调参数放在 url 的末尾以使用 jsonp 和 jq... ed: 哦,你指定了参数名称;这也有效,它比我习惯的更新和更长。
  • 感谢您闪电般的快速响应以及 jsfiddle。这行得通……@Guillermo Andres Fuentes Moral 的代码也是如此。我更喜欢 php,所以我会使用它,但是您会得到答案,因为您回答得如此之快!
【解决方案2】:

你可以在 PHP 中使用它

$site = file_get_contents("http://campusdata.uark.edu/api/buses?callback=&routeIds=8");
print_r(json_decode($site));

参考

json_encode

file_get_contents

【讨论】:

  • 是的,我错了回调是空的 json ;) @Sky
  • 这非常适合我想要的。我会标记为答案,但@TeaCode 打败了你。他们的回答也很有效,但我更喜欢 php。
【解决方案3】:

通过file_get_contents函数获取页面内容。删除非法字符。将json格式转成PHP数组:

<?php

$page = file_get_contents('https://campusdata.uark.edu/api/buses?callback=?&routeIds=8');
$page = substr($page, 0, -2);
$page = substr($page, 2);
var_dump (json_decode($page));

【讨论】:

  • 感谢添加删除非法字符位
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-29
  • 2020-03-29
  • 2013-04-26
  • 2015-12-09
  • 1970-01-01
  • 2015-04-03
相关资源
最近更新 更多