Using file_get_contents I get headers from sites

function page_title($url) { $fp = file_get_contents($url); if (!$fp) return null; $res = preg_match("/<title>(.*)<\/title>/siU", $fp, $title_matches); if (!$res) return null; // Clean up title: remove EOL and excessive whitespace. $title = preg_replace('/\s+/', ' ', $title_matches[1]); $title = trim($title); return $title; } 

Often there are sites without headers, I have default headers that I can save to the database so that 'my_title' => $item->my_title,

  $db->add(array_merge($item->only(['title', 'wareUrl', 'description', 'user', 'user_id', 'youtube', 'activatedate']), [ 'id' => (4 * 10000000) + $item->id, 'item_id' => $item->id, 'type' => 4, 'user_id' => $item->user['id'], 'youtube' => video_youtube(''.$item->wareUrl.''), 'title' => page_title(''.$item->wareUrl.''), // 'my_title' => $item->my_title, 'activatedate' => $item->activatedate, 'time' => microtime(true) ])); 

Help to create a construction } else { , so that in the absence of a header received via file_get_contents, the default header 'my_title' => $item->my_title,

Tried to set if inside $db->add(array_merge($item->only(['title', 'wareUrl', 'description', 'user', 'user_id', 'youtube', 'activatedate']), [ getting an error.

    2 answers 2

     'title' => page_title(''.$item->wareUrl.'') ? : $item->my_title, // $item->my_title дефолтный тайтл 

    only in page_title () would do return false; instead of return null; and at the end of this function, make a check on strlen for example:

     return strlen($title)>0 ? $title : false; 

    Well, or you can only in the page_title () function; replace all return null; on return $ item-> my_title and at the end check return strlen ($ title)> 0? $ title: $ item-> my_title; just look at the $ item scope, maybe you should add it inside the global $ item function;

    • Nsk, thanks, works! In page_title(); did so return $title; return strlen($title)>0 ? $title : false; return $title; return strlen($title)>0 ? $title : false; , right? - MicroRu
    • one
      @MicroRu only return strlen ($ title)> 0? $ title: false; before it return $ title; is not needed, it will work forward and things will not come to verification - Nsk
    • Thanks, it works like a clock. - MicroRu
     $title = 'defaultTitle'; if (preg_match("/<title>(.*)<\/title>/siU", $fp, $title_matches)) { $title = preg_replace('/\s+/', ' ', $title_matches[1]); $title = trim($title); } return $title;