0

I'm currently working on a website that requires me to load the image source of an tag from an external website via jQuery or PHP in order to embed that image on my page, is there any way to do this maybe by XPath?

EDIT: Based on additional research I did - both before asking the question here and after - I have now found the solution. Sergey Ligus has given me the right approach. The problem why file_get_contents didn't work was that the page seemed to block this kind of requests and I had to fake a user_agent via stream_context_create.

Example:

$context = stream_context_create([
        'http' => [
                'user_agent' => 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)',
        ],
]);

$html = file_get_contents('URL', false, $context);
$dom = new DOMDocument();
$dom->loadHTML($html);

$xpath = new DOMXPath($dom);
$result = '';
foreach ($xpath->query('XPATH') as $child) {
    $result .= $dom->saveHTML($child);
}
mrvinrsk
  • 19
  • 6
  • 1
    Have you tried fetch pages using `file_get_contents` or `curl` on the back-end side and then parse html content using `DOMXPath` and save parsed links for example in database? After that you can simply get links from db and render page via php with embed links without JQuery and tons of unnecessary requests to external website. But in this situation i would rather move parsing logic out of the website **scope/thread**, cause it will block user experience until all links will be fetched. – Sergey Ligus Dec 03 '21 at 00:11
  • I've tried file_get_contents but it doesn't work... When I print the assined variable i just get "Index of /" from my own webserver printed... – mrvinrsk Dec 03 '21 at 00:22
  • 1
    I don't understand the problem here. Can't you just set the external URL into the ? – E-telier Dec 03 '21 at 09:11

1 Answers1

0

I found something that might answer your question...
https://stackoverflow.com/questions/22580458/how-to-load-image-from-external-url-in-jquery-wordpress-theme
If this doesn't answer your question, I can tell you how to do this in vanilla JS :)

DaCuteRaccoon
  • 224
  • 2
  • 13