我正在使用xPath从另一个网站上抓取旅游日期(当然是经过许可的)。由于它在每次页面加载时都会更新,所以我考虑使用瞬态来存储数据。
不幸的是,我没有使用瞬态的经验,也没有让它工作。这是我的代码:
<?php
$html = file_get_contents(\'http://www.example.com\');
$doc = new DOMDocument();
libxml_use_internal_errors(TRUE); // disable libxml errors
if(!empty($html)) {
$doc->loadHTML($html);
libxml_clear_errors();
$xpath = new DOMXPath($doc);
// Get only the content needed
$termine = $xpath->query(\'//ul[@class="artistEvents"]/li\');
if ($termine->length > 0) {
foreach ($termine as $termin) {
$date = $xpath->query("div[@class=\'left\']/strong", $termin);
$location = $xpath->query("div[contains(@class,\'right\')]", $termin);
echo \'<tr>\';
// Date
if ($date->length > 0) {
$date = substr($date->item(0)->nodeValue, 3, 10);
$date = strftime("%d.%m.%Y", strtotime($date));
echo \'<td class="live-date">\' . $date . \'</td>\';
}
// Location
if ($location->length > 0) {
$location = substr($location->item(0)->nodeValue, 14);
$location = utf8_decode($location);
echo \'<td class="live-location">\' . $location . \'</td>\';
}
echo \'</tr>\';
}
}
else {
echo \'<p>No dates available.</p>\';
}
}
?>
非常感谢您对如何使用瞬态存储此查询的任何帮助!此外,我以前从未使用过xPath,因此如果我的代码需要任何改进(尽管它可以工作),我很乐意了解它。
非常感谢!
最合适的回答,由SO网友:czerspalace 整理而成
试试这样的方法,这样可以节省12个小时的时间。如果有什么不合理的地方,请告诉我。
<?php
$value = get_transient( \'value\' );
if ( false === $value ) {
$output = "";
$html = file_get_contents(\'http://www.example.com\');
$doc = new DOMDocument();
libxml_use_internal_errors(TRUE); // disable libxml errors
if(!empty($html)) {
$doc->loadHTML($html);
libxml_clear_errors();
$xpath = new DOMXPath($doc);
// Get only the content needed
$termine = $xpath->query(\'//ul[@class="artistEvents"]/li\');
if ($termine->length > 0) {
foreach ($termine as $termin) {
$date = $xpath->query("div[@class=\'left\']/strong", $termin);
$location = $xpath->query("div[contains(@class,\'right\')]", $termin);
$output .= \'<tr>\';
// Date
if ($date->length > 0) {
$date = substr($date->item(0)->nodeValue, 3, 10);
$date = strftime("%d.%m.%Y", strtotime($date));
$output .= \'<td class="live-date">\' . $date . \'</td>\';
}
// Location
if ($location->length > 0) {
$location = substr($location->item(0)->nodeValue, 14);
$location = utf8_decode($location);
$output .= \'<td class="live-location">\' . $location . \'</td>\';
}
$output .= \'</tr>\';
}
}
else {
$output .= \'<p>No dates available.</p>\';
}
}
$value = $output;
set_transient( \'value\', $value, 12 * HOUR_IN_SECONDS );
}
echo $value;
?>