웹 사이트 (예 : http://www.example.com/weather.htm ) 에서 도시의 온도 및 상대 습도에 대한 데이터를 얻고 싶습니다 .
이 웹 사이트의 소스 코드
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Weather</title>
</head>
<body>
<p><span><pre id='ming'>
18-7-2016
temperature
Hong Kong 20.3
London 16.8
Washington 15.2
relative humidity
Hong Kong 80%
London 75%
Washington 60%
</pre></span></p>
</body>
</html>
이전에 도시의 종류에 대한 배열을 정의한 다음 PHP Simple HTML DOM Parser를 사용하여 데이터를 얻습니다.
<?php
require "simple_html_dom.php";
$c=array("London","Washington","Hong Kong");
$temp=array();
$rh=array();
$date="";
$html = file_get_html('test.htm');
foreach($html->find('pre#ming') as $e)
$links[] = $e->innertext . '<br>';
print_r($links);
?>
$ link 배열이 표시됩니다.
Array ( [0] => 18-7-2016 temperature Hong Kong 20.3 London 16.8 Washington 15.2 relative humidity Hong Kong 80% London 75% Washington 60%
)
$ link에서 날짜, 온도 및 상대 습도 데이터를 가져 와서 $ date, $ temp 및 $ rh에 넣으려면 어떻게해야합니까 ($ temp 및 $ rh 정렬 : $ c)?
예를 들어 배열은 다음과 같아야합니다.
//$temp
Array
(
[0] => 16.8
[1] => 15.2
[2] => 20.3
)
//$rh
Array
(
[0] => 16.8
[1] => 15.2
[2] => 20.3
)
사이트의 콘텐츠 구조가 절대 변경되지 않는다고 가정
<?php
$mainArray = Array ( 0 => "18-7-2016 temperature Hong Kong 20.3 London 16.8 Washington 15.2 relative humidity Hong Kong 80% London 75% Washington 60%");
$dateArray = [];
foreach($mainArray as $data):
list($date,$arr) = explode(" ",$data,2);
$dateArray[] = $date;
// taking index
$tempIndex = strpos($arr,"temperature");
$rhIndex = strpos($arr,"relative humidity");
// taking substring with only city and its value
$tempString = substr($arr,strlen("temperature ") + $tempIndex,($rhIndex - (strlen("temperature ") + $tempIndex)));
$rhString = substr($arr,strlen("relative humidity ") + $rhIndex);
$cityArray = ["Hong Kong","London","Washington"];
$tempArray = [];
$rhArray = [];
foreach($cityArray as $city):
// extracting temperature values
if(strpos($tempString,$city) !== FALSE):
$tempArray[$city] = substr($tempString,strpos($tempString,$city) + strlen($city) + 1);
$splitArray = explode(" ",$tempArray[$city]);
$tempArray[$city] = $splitArray[0];
endif;
// extracting humidity values
if(strpos($rhString,$city) !== FALSE):
$rhArray[$city] = substr($tempString,strpos($tempString,$city) + strlen($city) + 1);
$splitArray = explode(" ",$rhArray[$city]);
$rhArray[$city] = $splitArray[0];
endif;
endforeach;
print_r($tempArray);echo "<br>";
print_r($rhArray);
endforeach;
print_r($dateArray);
?>
이것은 당신에게 다음과 같은 결과를 줄 것입니다
//temperature
Array ( [Hong Kong] => 20.3 [London] => 16.8 [Washington] => 15.2 )
//rh
Array ( [Hong Kong] => 20.3 [London] => 16.8 [Washington] => 15.2 )
//date
Array ( [0] => 18-7-2016 )
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다