【问题标题】:PHP scraping & preg_replacePHP 抓取和 preg_replace
【发布时间】:2014-03-03 10:21:36
【问题描述】:

我正在抓取一个气象站的天气信息并尝试将其转换为数据库格式。

我从网页上抓取了我需要的数据,但是当我尝试替换代码中的所有匹配项时,它只执行一次,而且我仍然不知道如何将其转换为数组。我正在尝试做的数组类似于(日期、时间、变量、值)。稍后我需要将数组放入 .txt 文件和数据库中。

这是我到目前为止所得到的:

 <?php;

 function scrape_between($data, $start, $end){
    $data = stristr($data, $start); // miro que quito todo antes de start
    $data = substr($data, strlen($start));  // Stripping $start
    $stop = stripos($data, $end);   // Getting the position of the $end of the data to scrape
    $data = substr($data, 0, $stop);    // Stripping all data from after and including the $end of the data to scrape
    return $data;   // devuelvo data entre las sentencias

}
// Defining the basic cURL function
$url = 'http://aprs.fi/?c=raw&call=EA4RKU-13&limit=1000&view=normal';
$ch = curl_init();  // Initialising cURL
curl_setopt($ch, CURLOPT_URL, $url);    // Setting cURL's URL option with the $url variable passed into the function
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); // Setting cURL's option to return the webpage data
$data = curl_exec($ch); // Executing the cURL request and assigning the returned data to the $data variable

$start="<div class='browselist_data'>";
$end = '</div>';

$data = scrape_between($data, $start, $end); // me quedo con la parte con span

curl_close($ch);    // Closing cURL
//echo strip_tags($data); // quita todos los tags html y php deja feo

 $z = count($data);

 echo "numero de datos: " .$z; //echo $data;   // Returning the data from the function
 $data1=preg_replace('/<b>.+?<\/b>/im', '' ,$data);
 //$data1=preg_replace('/<b>.+?<\/b>/im', '' ,$data);
 $data1=preg_replace('/$<a>.+?<\/a>/', '', $data1);
 echo $data1;

 ?>

【问题讨论】:

  • 仅供参考,这个词是“刮擦”,而不是“刮擦”——我已经提交了一个修改来改变它。

标签: php html arrays curl


【解决方案1】:

你可以使用类似这样的东西来代替 stristr 和 stripos:

<?
  ...

  preg_match_all("|<span class='raw_line'>(.*?)</span>|is",$data,$lines);
  echo count($lines[1]); //number of lines

?>

另外,你应该更好地解释每一行你需要什么?你期望什么样的输出?你能举个例子吗?

【讨论】:

  • 好的,我会试试这个,我需要的是从跨度到跨度的信息,从每一行我需要日期、时间、变量的名称:4030.25N/00320.45W_ 和价值。有 20 个变量,但有时一个值没有出现,所以我需要检查变量的名称。作为每一行的一个例子,我需要这个:2014-02-24 13:24:58 CET:>APRS,WIDE2-2,qAR,aprs.fi/… /> 2014-02-24 13:24:58 HS -0.07
  • 根据你的建议,我得到了行数,但没有得到数据,所以我同时使用它们
  • $lines[1] 包含您的行。做print_r($lines[1]),看看你得到了什么——你需要的行。
  • 我明白,但是手册说 $lines[1] 中的信息行数与没有跨度标签的匹配,所以我为什么不能访问 $lines[1] [$i]
  • 你做了print_r($lines[1])吗?这给了你什么?
猜你喜欢
  • 2013-07-17
  • 2015-09-22
  • 1970-01-01
  • 1970-01-01
  • 2014-06-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多