简体   繁体   中英

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 replace 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 the DOMDocument 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM