Search code examples
phpjqueryhtmlrelative-pathabsolute-path

HTML-PHP Relative Path to Absolute Path


Hi I am basically trying to fetch a page via php, get its html and change the html(to highlight some keywords) to a bit and display it as a overlay in my page(jquery).

//My php page data.php
<?php
$html=  file_get_contents($_GET['url']);
echo $html;
?>

//My jquery ajax request to data.php from page main.html
function test()
{  

        $.ajax({
            type: 'GET',
            url: 'data.php',
            data: 'url=http://www.developphp.com/view_lesson.php?v=338',
            cache: false,
            success: function(result) 
            {           
                 $("#overlay").append(result);

            }
        });
    }

}

As you can see, since the webpage uses relative URL, I am having issues displaying it in a overlay. I tried searching for a way to convert relative to absolute but did not find anything useful. Can you guys please point me in the right way?


Solution

  • I ilke @charlietfl's solution. However, somehow I think it gives more sense to manipulate the scraped content serverside before passing it to the client. You can do that by using DomDocument.

    The following code converts all <img> src relative paths to absolute paths before echoing the result. Use the same approch for the <a> tags href attributes and so on,

    error_reporting(0); //suppress DOM errors
    $basePath='http://www.developphp.com/'; //use parse_url to get the basepath dynamically
    $content=file_get_contents('http://www.developphp.com/view_lesson.php?v=338');
    $dom=new DomDocument();
    $dom->loadHTML($content);
    $images = $dom->getElementsByTagName('img');
    foreach ($images as $image) {
        $src=$image->attributes->getNamedItem("src")->value;
        if (strpos($basePath, $src)<=0) {
            $image->attributes->getNamedItem("src")->value=$basePath.$src;
        }
    }
    echo $dom->saveHTML();