Code: Get Article Reading Time using PHP
June 26, 2023 ⚊ 2 Min read ⚊ TUTORIALSTo calculate the reading time of an article using PHP, you can use the following PHP code:
<?php
function calculateReadingTime($text, $wordsPerMinute = 200) {
// Calculate the number of words in the text
$wordCount = str_word_count(strip_tags($text));
// Calculate the reading time in minutes
$readingTime = ceil($wordCount / $wordsPerMinute);
return $readingTime;
}
// Example usage
$articleText = "This is an example article. It contains some text that we want to calculate the reading time for.";
$readingTime = calculateReadingTime($articleText);
echo "Reading time: " . $readingTime . " minute(s)";
?>
In the above code, the calculateReadingTime
function takes two parameters: $text
represents the article text, and $wordsPerMinute
represents the average reading speed in words per minute (default is set to 200 words per minute).
The function first uses str_word_count
to count the number of words in the text. It then divides the word count by the average reading speed and uses ceil
to round up the result to the nearest whole number. This gives us the estimated reading time in minutes.
Finally, you can call the function with your article text and display the reading time.
Note: The function uses strip_tags
to remove any HTML tags from the text before counting the words, as it assumes the article may contain HTML markup. If your text doesn’t contain HTML tags, you can omit the strip_tags
function call.