我已经在php
中编写了一个脚本,以解析位于this url中表标题High School Directory by State
下的每个状态的链接。我的第一个函数fetch_item_links()
可以以正确的方式提取这些链接。我现在想做的是在fetch_info()
函数中提供这些URL,以便它将解析来自the target page的the red colored link
。
当我提供任何单独的URL进行测试时,第二个功能也可以正常使用,如this one。
但是,当我尝试运行整个脚本时,没有任何输出。也没有错误。
这是我到目前为止的尝试:
<?php
$url = 'http://www.directoryofschools.com/high-schools/US.html';
$prefix = 'http://www.directoryofschools.com';
function fetch_item_links($link,$base)
{
$html_doc = new DOMDocument();
@$html_doc->loadHtmlFile($link);
$content_xpath = new DOMXPath($html_doc);
$item_row = $content_xpath->query('//*[@class="online_college_list"]//tr//td//a[@title]');
$packtBook = array();
for ($i=0; $i <$item_row->length; $i++){
$title = $item_row->item($i)->getAttribute('href') . "<br/>";
$string = $base . str_replace("..", "", $title);
$packtBook[] = $string;
}
return $packtBook;
}
function fetch_info($link)
{
$html_doc = new DOMDocument();
@$html_doc->loadHtmlFile($link);
$content_xpath = new DOMXPath($html_doc);
$item_row = $content_xpath->query('//*[@class="online_college_list"]//tr//td//a[@title]');
for ($i=0; $i <$item_row->length; $i++){
$title = $item_row->item($i)->getAttribute('href') . "<br/>";
echo $title;
}
}
$items = fetch_item_links($url,$prefix);
foreach($items as $file){
fetch_info($file);
}
?>
如何使脚本正常运行?
答案 0 :(得分:1)
您要将<br/>
附加到fetch_item_links中的URL,这意味着您将无法通过loadHtmlFile()
加载它。将行更改为
$title = $item_row->item($i)->getAttribute('href');
实际上,在这两个地方,最好删除<br/>
,只在回显它时才将其附加到字符串上。