Reputation: 117
My code is like this which will access all the DOM elements. Now i want to add line number beside them. can anyone please help. thanks.
<?php
$dom = new domDocument;
// load the html into the object
$dom->loadHTMLFile('$url');
// keep white space
$dom->preserveWhiteSpace = true;
// nicely format output
$dom->formatOutput = true;
//get element by tag name
$htmlRootElement = $dom->getElementsByTagName('html');
$new = htmlspecialchars($dom->saveHTML(), ENT_QUOTES);
echo '<pre>' .$new. '</pre>';
?>
The code above would not out put give any line number. i want to do something like this.
<!DOCTYPE html>
1.<html>
2.<head>
3. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
4. <title></title>
5.</head>
6.<body>
7.</html>
Any suggestion please. thanks.
Upvotes: 2
Views: 313
Reputation: 181
Just split the string by new lines, and print out the line number followed by the line:
$lines = preg_split( '/\r\n|\r|\n/', $new );//split the string on new lines
echo "<pre>";
foreach($lines as $lineNumber=>$line){
echo "\r\n" . $lineNumber . ". " . $line;
}
echo "</pre>";
Upvotes: 1
Reputation: 2707
$lines = explode(PHP_EOL, $html);
There's my hint, I'm sure you can figure the rest out. There are already PHP libs for this btw, like GeSHi
Oh, and your code has a small error.
Where you're loading the HTML, you do '$url'
, which literally means $url
, not whatever your variable it. Use double-quotes or none at all.
Upvotes: 1