PHP - How to count lines of code in an application [duplicate]

醉酒当歌 提交于 2019-12-03 00:51:32

To do it over a directory, I'd use an iterator.

function countLines($path, $extensions = array('php')) {
    $it = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($path)
    );
    $files = array();
    foreach ($it as $file) {
        if ($file->isDir() || $file->isDot()) {
            continue;
        }
        $parts = explode('.', $file->getFilename());
        $extension = end($parts);
        if (in_array($extension, $extensions)) {
            $files[$file->getPathname()] = count(file($file->getPathname()));
        }
    }
    return $files;
}

That will return an array with each file as the key and the number of lines as the value. Then, if you want only a total, just do array_sum(countLines($path));...

Srisa

You can use the file function to read the file and then count:

$c = count(file('filename.php'));

Using ircmaxell's code, I made a simple class out of it, it works great for me now

<?php
class Line_Counter
{
    private $filepath;
    private $files = array();

    public function __construct($filepath)
    {
        $this->filepath = $filepath;
    }

    public function countLines($extensions = array('php'))
    {
        $it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($this->filepath));
        foreach ($it as $file)
        {
           // if ($file->isDir() || $file->isDot())
           if ($file->isDir() )
            {
                continue;
            }
            $parts = explode('.', $file->getFilename());
            $extension = end($parts);
            if (in_array($extension, $extensions))
            {
                $files[$file->getPathname()] = count(file($file->getPathname()));
            }
        }
        return $files;
    }

    public function showLines()
    {
        echo '<pre>';
        print_r($this->countLines());
        echo '</pre>';
    }

    public function totalLines()
    {
        return array_sum($this->countLines());
    }

}

// Get all files with line count for each into an array
$loc = new Line_Counter('E:\Server\htdocs\myframework');
$loc->showLines();

echo '<br><br> Total Lines of code: ';
echo $loc->totalLines();

?>
$fp = "file.php";
$lines = file($fp);
echo count($lines);

PHP Classes has a nice class for counting lines for php files in a directory:

http://www.phpclasses.org/package/1091-PHP-Calculates-the-total-lines-of-code-in-a-directory.html

You can specify the file types you want to check at the top of the class.

a little dirty, but you can also use system / exec / passthru wc -l *

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!