我是一個剛開始的程序員,試圖製作一個簡單的應用程序,只需要一個網站並返回值。比較字符串,使用較短的字符串
我試圖做一些我認爲很簡單的事情,但經過搜索和嘗試後,已經放棄了只是問。
用我的刮板,我返回三個變量:$ TITLE1,$標題2,並$ TITLE3。所有的$標題都來自我嘗試查找文章名稱的不同方法。理想情況下,我只需要尋找一個並完成,但有些網站存儲數據不同(有些通過元標記,隱藏的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
所以我的代碼將在最短的$標題在字符串長度(不是空值)中,並將值賦給$ realtitle。
感謝您的幫助!如果你需要更多的細節,請問!
編輯
我的繼承人完整的代碼:它的工作原理,直到在$稱號的是一個 「」,那麼$ 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/>';
?>
恩,也許是一個愚蠢的問題,但如果所有三個標題都是「空」,你會怎麼做? – hakre
@ hakre ..我不確定,我必須弄清楚。感謝您指出這一點 – Muhambi