使用xpath或其他方式获取图像

时间:2012-03-15 11:06:22

标签: php html xml xpath getattribute

我需要从远程页面获取图像,我尝试过xpath但我被告知它不会工作因为img没有nodevalue 然后我被建议使用getAttribute,但我不知道如何让它工作。

有什么建议吗? 这是我的代码

<?php

libxml_use_internal_errors(true);

//Setting content type to xml!
header('Content-type: application/xml');

//POST Field name is bWV0aG9k

$url_prefix = $_GET['bWV0aG9k'];

$url_http_request_encode = strpos($url_prefix, "http://");


//Checking to see if url has a http prefix
if($url_http_request_encode === false){
    //does not have, add it!
    $fetchable_url_link_consistancy_remote_data = "http://".$url_prefix;

}
else
    //has it, do nothing
{
   $fetchable_url_link_consistancy_remote_data = $url_prefix;
}



//Creating a new DOM Document on top of pre-existing one 
$page = new DOMDocument();

//Loading the requested file
$page->loadHTMLFile($fetchable_url_link_consistancy_remote_data);

//Initliazing xpath
$xpath = new DOMXPath($page);

//Search parameters 

//Searching for title attribute
$query = "//title";
//Searching for paragraph attribute
$query1 = "//p";
//Searching for thumbnails
$query2 = "//img";


//Binding the attributes to xpath for later use
$title = $xpath->query($query);

$paragraph = $xpath->query($query1);

$images = $xpath->query($query2);




echo "<remotedata>";
//Echoing the attributes
echo "<title-render>".$title->item(0)->nodeValue."</title-render>";
echo "<paragraph>".$paragraph->item(0)->nodeValue."</paragraph>";
echo "<image_link>".$images->item(0)->nodeValue."</image_link>";
echo "</remotedata>";

?>

2 个答案:

答案 0 :(得分:1)

你应该获得图像标签的source属性。

$images->item(0)->getAttribute('src');

答案 1 :(得分:1)

如果这是正常的xhtml,img没有值,你需要img / @src的值