purpleslurple / PurpleSlurple

PurpleSlurple transcodes web pages to make them granularly accessible.
GNU General Public License v2.0
0 stars 0 forks source link

Refactor purpleslurple function #103

Closed purpleslurple closed 9 months ago

purpleslurple commented 10 months ago

function purpleslurple($url) { // PurpleSlurple takes a URL and returns the page with purple numbers. // The purple numbers anchors that link to the headings and paragraphs // of the page - providing fine-grained addressability. $web_page = file_get_contents($url); $dom = new DOMDocument; $dom->loadHTML($web_page); $xpath = new DOMXPath($dom); $line_number = 0; foreach ($xpath->query('//*[self::h1 or self::h2 or self::h3 or self::h4 or self::h5 or self::h6 or self::p]') as $tag) { // create a new anchor tag with the purple number and add it to the beginning of the tag $anchor = $dom->createElement('a', '[{}]'.format($line_number)); $anchor->setAttribute('href', '#purple'.format($line_number)); $anchor->setAttribute('id', 'purple'.format($line_number)); $tag->insertBefore($anchor, $tag->firstChild); $line_number += 1; }

// return the modified HTML
return $dom->saveHTML();

}

purpleslurple('https://purpleslurple.com');