正在分析单词之间有空格的关键字


Parsing keywords having space in-between the words

我从网站上获取数据,当我解析"数学、化学、科学"等单个单词时,下面提到的脚本运行良好。然而,如果我试图解析一个中间包含空格的关键字,如"商业数学"等,浏览器就会永远加载,它似乎不起作用。请引导我…

<?php
include("simple_html_dom.php");
$keywords = "business math,chemistry,science";
$keywords = explode(',', $keywords);
foreach($keywords as $keyword) {
    echo '<br><b><font color="red">Keyword: </font><font color="blue">'.$keyword.'</font></b><br>';
    $html = file_get_html('http://www.tutorvista.com/search/'.$keyword);
    $i = 1;
    foreach($html->find('div[style=padding:20px; border-top:thin solid #DDDDDD; border-bottom:none;]') as $element) {
        foreach($element->find('div[class=entry-abstract]') as $div) {
            $title[$i] = $div->plaintext.'<br><br>';
        }
        $i++;
    }
    print_r($title);
}
?>

问题就在这一行:

$html = file_get_html('http://www.tutorvista.com/search/'.$keyword);

该函数内部使用file_get_contents(),它不接受空格,并且需要使用urlencode()对URI进行编码。

试试这个:

$html = file_get_html( urlencode('http://www.tutorvista.com/search/'.$keyword) );

参考:

http://sourceforge.net/p/simplehtmldom/code/208/tree/trunk/simple_html_dom.php#l76http://php.net/manual/en/function.file-get-contents.php