How can I load an external page with PHP and replace content on that page?
I'm building a PHP app that allows a user to upload an ad and preview it on specific pages of a specific website. Right now, I'm doing it by taking screenshots of the webpage, removing the ads, and placing my own s. This seems pretty stupid.
What would be the best way to get the contents of a URL and rep开发者_运维百科lace code that appears between a certain on that page?
- Load the page source into a
DOMDocument
object - Do a search and replace using
XPath
on theDOMDocument
object
Example:
<?php
$dom = new DOMDocument();
$dom->strictErrorChecking = false;
$dom->loadHTMLFile("http://www.example.com");
$xpath = new DOMXPath($dom);
$logoImage = $xpath->query("//div[@id='header-logo']//a//img")->item(0);
$logoImage->setAttribute('src', 'http://www.google.com/images/logos/ps_logo2.png');
$logoLink = $xpath->query("//div[@id='header-logo']//a")->item(0);
$logoLink->setAttribute('href', 'http://www.google.com/');
echo $dom->saveHTML();
?>
The example loads the source of example.com
and replaces the logo with google.com
's logo and a link to google.
The code does not have any validation but should be pretty easy to modify for your needs :)
I am not sure about complete situation that how you would like to perform this action. However on base of your question best way is to use Ajax.
Through Ajax pass detail of page you want to display and in php filter page as you want to display and return desired result.
And at the end of Ajax request display your result in particular location.
Even in JavaScript you can filter result as you like returned by Ajax request.
精彩评论