Search code examples
phpparenthref

Using php to get parent element of link with URL


I'm trying to implement a "find and replace" system for broken links. The problem is, for some links there are no replacements. So, I need to comment out certain li elements. You can see my code below to do this. (I'm starting with an HTML form).

<?php

$brokenlink = $_POST['brokenlink'];
$newlink = $_POST['newlink'];

$brokenlink = '"' . $brokenlink . '"';
$newlink = '"' . $newlink . '"';

$di = new RecursiveDirectoryIterator('hugedirectory');
foreach (new RecursiveIteratorIterator($di) as $filename => $file) {
  //  echo $filename . ' - ' . $file->getSize() . ' bytes <br/>';

    $filetoedit = file_get_contents($file);
    if(strpos($filetoedit, $brokenlink)) {

    echo $brokenlink . "found in " . $filename . "<br/>";
    $filetoedit = str_replace($brokenlink, $newlink, $filetoedit);
    file_put_contents($filename, $filetoedit);

    }

}

?>

What I want to accomplish is this: If I have a URL, I want to be able to find its li parent. For instance, I want PHP to be able to comment out the code below if the user inputs http://www.espn.com in an HTML form, I want php to find this element on my server:

 <li><a href="http://www.espn.com" target="_blank" data-new="20120627">Sports</a></li>

And replace it with this:

 <!-- <li><a href="http://www.espn.com" target="_blank" data-new="20120627">Sports</a></li> -->

Is this possible? Thanks.


Solution

  • I would try using this to parse the DOM.

    http://simplehtmldom.sourceforge.net/

    You can set a class to all the ones you want comment out. Then use this tool to find those classes and comment them all out at once.