Document Object Model函数从数据库中获取一组链接,并逐一处理它们


Document Object Model function to take an array of links from a database and process them one by one

我一直在尝试对我试图构建的程序进行故障排除,我已经设法找出了问题的原因,但要解决它,我一直没有成功。

我使用php中的文档对象模型函数从数据库中获取一个链接数组,并逐一处理它们,但在@$doc->loadHTMLFile("$alllinks");行中,此函数接受数据库中的数组值时出现问题。

然而,我感到困惑的是,如果我创建一个通用数组,它可以工作,但从数据库(或其他一些方法)来看,它只是失败了。

这是一个有效的版本:

<?php session_start();

// EDIT: Use a custom function to do the
// reverse of SORT_NUMERIC with asort
function height_compare($a1, $b1)
{
    if ($a1 == $b1) {
        return 0;
    }
    return ($a1 > $b1) ? -1 : 1;
}
$all_links = array('http://example.com/klvvobj','http://example.net/s/109228626');
foreach($all_links as $alllinks){
$doc = new DOMDocument();
// Okay this is HTML is kind of screwy
// So we're going to suppress errors
@$doc->loadHTMLFile("$alllinks");
// Get all images
$images_list = $doc->getElementsByTagName('img');
$images = array();
foreach($images_list as $image) {
  // Get the src attribute
  $image_source = $image->getAttribute('src');
  if (substr($image_source,0,7)=="http://"){
  $image_size_info = getimagesize($image_source);
  $images[$image_source] = $image_size_info[1];
  print_r($images);
  }
}

// Do a numeric sort on the height
uasort($images, "height_compare");
$tallest_image = array_slice($images, 0,1);
$mainimg = key($tallest_image);
echo "<img src='$mainimg' />";
}
print_r($images);
?> 

这是一个失败的版本:

<?php session_start();
include 'functions.php';
$query = mysql_query("SELECT * FROM links");
        function height_compare($a1, $b1)
{
    if ($a1 == $b1) {
        return 0;
    }
    return ($a1 > $b1) ? -1 : 1;
}
while($result = mysql_fetch_array($query)) {
$link = $result['link'];
$doc = new DOMDocument();
// Okay this is HTML is kind of screwy
// So we're going to suppress errors
@$doc->loadHTMLFile($link);
// Get all images
$images_list = $doc->getElementsByTagName('img');
$images = array();
foreach($images_list as $image) {
  // Get the src attribute
  $image_source = $image->getAttribute('src');
  if (substr($image_source,0,7)=="http://"){
  $image_size_info = getimagesize($image_source);
  $images[$image_source] = $image_size_info[1];
  print_r($images);
  }
}

// Do a numeric sort on the height
uasort($images, "height_compare");
$tallest_image = array_slice($images, 0,1);
$mainimg = key($tallest_image);
echo "<img src='$mainimg' />";
}
                     echo '<a href="logout.php">Log out</a>';
?>

带有:

@$doc->loadHTMLFile("'$link'");

即使$link包含正确/可读的地址,结果也会类似于:

@$doc->loadHTMLFile("'http://...'");

并且CCD_ 4不是正确的地址。

(参见'

更改为:

@$doc->loadHTMLFile($link);


此外,请不要使用@进行错误超压:使用

libxml_use_internal_errors(true);

libxml_get_errors();

当处理有问题的xml/html时。看见http://php.net/manual/function.libxml-use-internal-errors.php


另一个补充:

你不需要那种东西。如果你只想要"最高的图像"使用:

$mainimg = array_search(max($images), $images);