The simplest way to get lyrics using Regular Expressions with PHP Code

Authors: CodeToday | PHP Code | Views: 423 | Posted: 03 AM: 09/11/2017

Today I will have practice to retrieve data from a lyrics page, this article related to structural analysis of html page by Regular Expressions PHP. The function use here is preg_match

For example, here is this page: https://www.azlyrics.com/lyrics/taylorswift/lovestory.html

The steps to perform are as follows

  1. Get data of html page use curl_init()
  2. preg_match will take the lyrics we need
After completing the above two steps we will have the results as below

The simplest way to get lyrics using Regular Expressions with PHP Code

PHP Source Code

<?
$url = 'https://www.azlyrics.com/lyrics/taylorswift/lovestory.html';
echo '<pre>'.$url.'</pre>';
$ch = curl_init();
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($ch, CURLOPT_HTTPGET, 1 );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($ch, CURLOPT_FOLLOWLOCATION , 1 );
curl_setopt($ch, CURLOPT_FOLLOWLOCATION , 1 );
curl_setopt($ch, CURLOPT_URL, $url );
curl_setopt($ch, CURLOPT_REFERER, $ref );
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // Get data from url using https     
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
$data = curl_exec($ch);
curl_close($ch);
preg_match('/Sorry about that. -->(.*?)</div>/si', $data, $lyrics);	
echo $lyrics[1];
?>

Based by samples you can you get lyrics of some other websites as metrolyrics.com, lyricsfreak.com ... and other data you want.

Note: You can make a request under comments, I will try to meet some of your requirements

If you have any questions, please leave a message below