Вытяните HTML-контент с удаленного веб-сайта и отобразите его на странице

Некоторое время я работал над этим, и я был в тупике. Я пытаюсь вытащить содержимое из определенного div на удаленную страницу веб-сайта, а затем вставить этот html в div на моем собственном веб-сайте. Я знаю, что вы не можете использовать jQuery только методы .ajax, .load или .get для этого типа операций.

Вот HTML-код удаленной страницы:

<html> <body> <div class="entry-content"> <table class="table"> ...table #1 content... ...More table content... </table> <table class="table"> ...table #2 content... </table> <table class="table"> ...table #3 content... </table> </div> </body> </html> 

Цель. Я пытаюсь извлечь html из первой таблицы удаленной страницы. Итак, на моем веб-сайте я хотел бы, чтобы следующий html был загружен и помещен в div id = "fetched-html":

 <table class="table"> ...table #1 content... ...More table content... </table> 

Вот где я нахожусь с моей PHP-функцией до сих пор:

 <?php function pullRaspi_SDImageTable() { $url = "http://www.raspberrypi.org/downloads"; $curl = curl_init($url); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); $output = curl_exec($curl); curl_close($curl); // Create new PHP DOM document $DOM = new DOMDocument; // Load html from curl request into document model $DOM->loadHTML($output); // Get 1st table $output = $DOM->firstChild->getElementsByTagName('table'); return $output; } ?> 

Окончательный результат должен выглядеть так на моей местной странице веб-сайта:

 <div id="fetched-html"> <table class="table"> ...table #1 content... ...More table content... </table> </div> 

Вот еще одна возможность PHP-функции?

 <?php function pullRaspPi_SDImageTable() { // Url to fetch $url = "http://www.raspberrypi.org/downloads"; $ch = curl_init($url); $fp = fopen("raspberrypi_sdimagetable.txt", "w"); curl_setopt($ch, CURLOPT_FILE, $fp); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_BINARYTRANSFER, true); // Write html source to variable $rasp_sdimagetable = curl_exec($ch); // Close curl request curl_close($ch); return $rasp_sdimagetable; } // Then in the head of the html, add this jQuery: <script type="text/javascript"> $("#fetched-html").load("<?php pullRaspPi_SDImageTable(); ?> table.table:first"); </script> 

Проблема в том, что ни одна из функций не работает. 🙁 Есть предположения?

    Извлечение фрагмента HTML с веб-сайта – это легкий ветерок с простым ходом, и вы можете сделать что-то вроде:

     function pullRaspi_SDImageTable() { $filename = '/tmp/downloads.html'; /// Where you want to cache the result $expiry = 600; // 10 minutes $output = ''; if (!file_exists($filename) || time() - $expiry > filemtime($filename)) { // There is no cache, so fetch the results from remote server require_once('simple_html_dom.php'); $html = file_get_html('http://www.raspberrypi.org/downloads'); foreach($html->find('div.entry-content table.table') as $elem) { $output .= (string)$elem; } // Store the cache file_put_contents($filename, $output); } else { // Pull the content from the cahce $output = file_get_contents($filename); } return $output; } 

    Что даст вам table.table HTML

    вы не можете использовать только методы jQuery .ajax, .load или .get для этого типа операции

    Да, вы можете, НО удаленный веб-сайт должен дать вам разрешение на это. Просто вставив iframe и используя обычные функции DOM, вы могли бы, если бы не пересекали ограничения домена.

    Вы можете получить FULL-страницу только с помощью php (используя общие функции include, require и т. Д. И передавая URL-адрес веб-сайта, но в том же случае вам необходимо авторизоваться.