我正在获取一个页面,该页面包含一些样式标记、表和其他非重要内容。我把它存储在一个瞬态中,并用AJAX 获取它
$result_match = file_get_contents( 'www.example.com' );
set_transient( 'match_results_details', $result_match, 60 * 60 * 12 );
$match_results = get_transient( 'match_results_details' );
if ( $match_results != '') {
$html = new simple_html_dom();
$html->load($match_results);
$out = '';
$out .= '<div class="match_info_container">';
if (!empty($html) && is_object($html)) {
foreach ($html->find('table') as $table => $table_value) {
$out .= preg_replace('/href="?([^">]+)"/', '', $table_value);
}
}
$out .= '</div>';
wp_die ( $out );
} else {
$no_match_info = esc_html__('No info available', 'kompisligan');
wp_die($no_match_info);
}
现在表有锚,我需要删除它,所以我使用preg_replace
来查找任何锚并清空它。我知道你可以用find()
方法处理内容,但我没有成功。
现在我想去掉整个<tfoot>
标签,以及它包含的内容。
但每次我试图"找到"某个东西时,ajax都会返回错误,这意味着我的代码中有错误。
如何使用simple_html_dom
操作已找到元素的内容?我试着输出$html
的内容,这样我就可以看到我会得到什么,但我的AJAX调用永远持续,我无法得到它。
您可以尝试使用内置DOMDocument而不是simple_html_dom。但是,如果Ajax调用超时,可能会出现另一个问题(无法加载example.com)。
if ( $match_results != '') {
$html = new DOMDocument();
// Suppress errors
@$html->loadHTML($match_results);
$out = '<div class="match_info_container">';
// Remove all "href" tags from <a>
foreach($html->getElementsByTagName('a') as $href)
$href->setAttribute('href', '');
// Remove Tfoot
foreach($html->getElementsByTagName('tfoot') as $tfoot)
$tfoot->parentNode->removeChild($tfoot);
// Put the contents of every <table> in the div.
foreach($html->getElementsByTagName('table') as $table)
$out .= $table->nodeValue;
$out .= '</div>';
wp_die ( $out );
} else {