我是一名初级程序员,试图制作一个简单的应用程序,只抓取网站并返回值。
我正在尝试做一些我认为很简单的事情,但是在搜索和尝试之后,我放弃了只是问。
使用我的爬虫,我返回三个变量:$title1、$title2和$title3。所有的 $title 都来自我试图找到文章名称的不同方法。理想情况下,我只需要寻找一个并完成,但有些网站以不同的方式存储数据(有些通过元标记、隐藏的 div、元素等)。
我需要一种方法来执行以下伪代码:
if $title1, $title2, $title3 != null { // don't count a string if it is null
$title1_stringlength = string_length($title1) //find string length of the $titles
$title2_stringlength = string_length($title2)
$title3_stringlength = string_length($title3)
$realtitle = $lowestvalueofstringlength; // $realtitle gets whichever $title is shortest in length, not counting any null $title's
}
这是我为什么需要这样做的一个例子:
echo $title1; //echoes "Exercise Daily"
echo $title2; //echoes "null"
echo $title3; //echoes "Exercise Daily - And More advice on SaveTheTwinkie.org"
$realtitle = $title1;//should be $title1 because it was shortest that wasn't null
//or a different example from another site
echo $title1; //echoes "Wow look at this Article Title!"
echo $title2; //echoes "null"
echo $title3; //echoes "Wow look at this Article Title! - from StupidArticles.tv"
$realtitle = $title1;//should be $title1 because it was shortest that wasn't null
因此,我的代码将查找字符串长度中最短的 $title(不为空)并将值赋予 $realtitle。
感谢您的任何帮助!如果您需要更多详细信息,请询问!
编辑
这是我的完整代码:它一直有效,直到 $title 之一是“”,然后 $realtitle 也变为“”
<?php
$sites_html = file_get_contents($url);
$html = new DOMDocument();
@$html->loadHTML($sites_html);
$title1 = null; //reset
$title2 = null; //reset
$title3 = null; //reset
//Get all meta tags and loop through them.
foreach($html->getElementsByTagName('meta') as $meta) {
if($meta->getAttribute('property')=='og:title'){
//Assign the value from content attribute to $title1
$title1 = $meta->getAttribute('content');
}
}
foreach($html->getElementsByTagName('h1') as $div) {
if($div->getAttribute('itemprop')=='name'){
$title2 = $div->nodeValue;
}
}
foreach($html->getElementsByTagName('h1') as $div) {
if($div->getAttribute('class')=='fn'){
$title3 = $div->nodeValue;
}
}
$realtitle = array_reduce(array($title2, $title1, $title3), function($a, $b) {
return strlen($a) && $a != 'null' && strlen($a) < strlen($b) ? $a : $b;
}, null);
echo 'metaogtitle: '.$title1 . '<br/><br/><br/><br/><br/>';
echo 'name: '.$title2. '<br/><br/><br/><br/><br/>';
echo 'name2: '.$title3. '<br/><br/><br/><br/><br/>';
echo 'realtitle: '.$realtitle. '<br/><br/><br/><br/><br/>';
?>