如何構建DOMXPath查詢以返回DOMDocument上唯一的img元素的src屬性?使用img標記返回元素的DOMXPath查詢
注意:對於具有多個img元素的DOMDoc,我能夠成功使用 - > getElementsByTagName方法,但是此方法對於僅包含一個img元素的DOMDoc僅返回空值。請注意,我試圖人爲地向文檔添加一個img元素。當元素成功添加時,隨後調用getElementsByTagName僅返回新添加的元素(文檔包含多個img元素,它們都會很好地返回,包括新添加的元素)。
而且,我嘗試下面的代碼,類似網頁的建議,但ID不會回事情:
$imageLink = $_POST['link'];
$external = new DOMDocument;
$external ->loadHTMLFile($imageLink);
$xpath = new DOMXPath($external);
$elements = $xpath->query("//*[@name='img']");
foreach ($elements as $node)
{
$element[] = $node;
echo $node->getAttribute('src');
}
print_r($node);
我也嘗試過所有通過重複使用使用節點的循環 - > childNodes並回顯信息,但這也不起作用。我花了整整一天的時間。如果有人可以告訴我具體如何刮取一個img元素的信息,或者直接指向一個可靠的PHP DOM教程,我會非常感激。
謝謝,
P.S. 當我輸入url的時候,下面的代碼可以正常工作,如this one,但不包含僅包含一個圖像的鏈接,例如this。我目前正在研究DOMXPath解決方案。謝謝:
<?php
if(isset($_POST['link'])){
$link = $_POST['link'];
$scrapings = "";
$article = new DOMDocument;
$article ->loadHTMLFile($link);
$titles = $article->getElementsByTagName("title");
foreach($titles as $title){
echo $title->nodeValue, PHP_EOL;
}
$images = $article->getElementsByTagName("img");
foreach($images as $image){
$source = $image->getAttribute("src");
$scrapings .= '<img src="'.$source.'" alt="default">';
}
}
?>
<!DOCTYPE html>
<html>
<head></head>
<body>
<form method="POST" action="otherScraper.php">
<input type="text" name="link">
<input type="submit" value="submit">
</form>
<?php echo $scrapings; ?>
</body>
</html>
這是上面的代碼的一個版本,但使用DOMXPath代替。完全相同的問題發生在與大多數鏈接一起工作的地方,但不是包含單個img元素的鏈接。是一些關於我如何建立文檔?:
<?php
if(isset($_POST['link'])){
$link = $_POST['link'];
$scrapings = "";
$article = new DOMDocument;
$article ->loadHTMLFile($link);
$xpath = new DOMXPath($article);
$imgs = $xpath->query('//img');
$titles = $article->getElementsByTagName("title");
foreach($titles as $title){
echo $title->nodeValue, PHP_EOL;
}
foreach($imgs as $image){
$source = $image->getAttribute("src");
$scrapings .= '<img src="'.$source.'" alt="default">';
}
}
?>
<!DOCTYPE html>
<html>
<head></head>
<body>
<form method="POST" action="image_scraper.php">
<input type="text" name="link">
<input type="submit" value="submit">
</form>
<?php echo $scrapings; ?>
</body>
</html>
您給出的鏈接不起作用的是鏈接到圖像而不是包含圖像的html文件。 – Musa
@MUSA這麼簡單...很明顯,謝謝!我不必處理任何東西,只需保存正在提交的網址,並使用相同的網址作爲我的圖像源。歡呼聲 – Theramax