我正在尝试在页面上使用ID抓取特定的div



我想抓取一个页面的内容,实际上只是从该页面中抓取一个div,并在网页的一个小div中显示给用户。我只需要从一个carfax页面的信息,需要用户凭据,所以我不能发布确切的代码,但我尝试使用google.com和有同样的问题,所以解决方案应该交叉。

现在我已经试过了:

$webPage = file_get_contents('http://www.google.com');
$doc = new DOMDocument();
$doc->loadHTML($webPage);
$div = $doc->getElementById('lga');//this is the id to the div holding the image above the textbox
//echo $webPage;//this displays www.google.com minus the image. I imagine because of the file path
//var_dump($div);//this display "object(DOMElement)#2 (0) { }" and I'm not sure what that means
//echo $div;//this has a server error

我也在看simple_html_dom。php试图找出

你可以这样做:

/**
 * Downloads a web page from $url, selects the the element by $id
 * and returns it's xml string representation.
 */
function getElementByIdAsString($url, $id, $pretty = true) {
    $doc = new DOMDocument();
    @$doc->loadHTMLFile($url);
    if(!$doc) {
        throw new Exception("Failed to load $url");
    }
    // Obtain the element
    $element = $doc->getElementById($id);
    if(!$element) {
        throw new Exception("An element with id $id was not found");
    }
    if($pretty) {
        $doc->formatOutput = true;
    }
    // Return the string representation of the element
    return $doc->saveXML($element);
}
// call it:
echo getElementByIdAsString('http://www.google.com', 'lga');

最新更新