代码如下。我想在file_get_contents之后使用链接URL的id结果集解析表。这是正确的方法吗?我是php,html和javascript的新手,所以请解释最简单的步骤。对我来说很难的是将html,php和js结合起来并使其正常工作。
当我将其保存为php文件并打开它时,它只会显示[object HTMLCollection]。为什么?这有什么问题?
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php
$var = file_get_contents("link here");
// echo $var;
?>
<script>
var x = document.getElementsByClassName("result-set");
document.write(x)
</script>
</body>
</html>
答案 0 :(得分:0)
在您的代码中,您使用Javascript返回节点集合,这就是您收到消息“htmlCollection”的原因,但是因为远程站点中的HTML不存在于您的html页面中,所以无论如何它都将是一个空集合。您可以使用您已经显示的方法,但是您需要回显来自file_get_contents
的响应,以便各种表元素出现在您的html中 - 但它看起来很乱,并且不是有效的html。
另一种方法,使用DOMDocument
和XPath
- 示例。
$url='http://wttv.click-tt.de/cgi-bin/WebObjects/nuLigaTTDE.woa/wa/groupPage?championship=M%C3%BCnster+16%2F17&group=275320';
/* simple variable to branch logic */
$clonetable=true;
/* try to prevent errors */
libxml_use_internal_errors( true );
/* create the DOMDocument object ready to receive html from remote url */
$dom=new DOMDocument;
/* We need another instance of DOMDocument to clone nodes from source url */
if( $clonetable ) $html=new DOMDocument;
/* use some of the defined properties for libxml */
$dom->validateOnParse=false;
$dom->standalone=true;
$dom->strictErrorChecking=false;
$dom->recover=true;
$dom->formatOutput=false;
$dom->loadHTML( file_get_contents( $url ) );
/* Capture errors */
$parse_errs=serialize( libxml_get_last_error() );
libxml_clear_errors();
/* create an X-Path object ready to query the DOM */
$xp=new DOMXPath( $dom );
/* Query to find tables with given class */
$col=$xp->query('//table[@class="result-set"]');
/*
If the query succeeds, iterate through elements.
Technically you could use 1 xpath query to find the
table cells directly but you would have less control
over whether or not to display items etc etc
*/
if( $col && !empty( $col ) ){
foreach( $col as $index => $table ){
if( $clonetable ){
/* Create a copy/clone of existing tables from remote page */
$clone=$table->cloneNode(true);
/* Add these clones to the second DOMDocument instance */
$html->appendChild( $html->importNode($clone,true) );
} else {
/* Another xpath query to find the table cells and work with the data therein */
$cells=$xp->query('tr/td',$table);
if( $cells && !empty( $cells ) ){
foreach( $cells as $cell ){
/* do something with the table cell data */
echo $cell->nodeValue . '<br />';
}
}
}
}
/* Display the cloned tables as they were in original document, minus CSS */
if( is_object( $html ) ) echo $html->saveHTML();
}
if( !empty( $parse_errs ) ){
print_r($parse_errs);
}