2013-06-24 7 views
0

Так что я пытаюсь захватить последние новости с веб-сайта и включить его самостоятельно. Этот сайт использует Joomla (ugh), и в результате содержимого hrefs отсутствует базовый href. поэтому ссылки будут содержать contensite.php? Blablabla. которые приведут к ссылкам http://www.mysite.com/contensite.php?blablablapreg_replace in simple html dom

Так что я подумал о замене 'http: //' на 'http://www.basehref.com' перед тем, как эхо-выход. но мои знания останавливаются здесь. Wich я должен использовать? preg_replace, str_replace? я не уверен.

+0

Я попробовал оба tho, так вот почему im ask lol – defiancenl

+0

некоторые люди могут подумать, что это глупо, что я даже не думаю о настройке base href в голове ... но это не будет работать для меня, так как это заменит все hrefs на моем сайт к цели ba se href – defiancenl

ответ

0

поэтому я не смог (так как мне не хватает знания соответствия preg), чтобы исправить неработающие ссылки, вместо этого заменив их другой ссылкой и заменив класс ссылки на мой класс fancybox, таким образом он откроет исходный сайт в fancybox.

include_once('db_connect.php'); 
// connect to my db 

include_once('dom.php'); 
// include html_simple_dom! 

$dom = file_get_html('http://www.remotesite.com'); 
// get the html content of a site and pass it through html simple dom ! 

$elem = $dom->find('div[class=blog]', 0); 
// set the div to target for ! 



$pattern = '/(?<=href\=")[^]]+?(?=")/'; 
$replacement ='http://www.remotesite.com'; 
$replacedHrefHtml = preg_replace($pattern, $replacement, $elem); 
// replacement 1 
// replace the broken links (base href is missing , joomla sucks , period !) 
// im to lazy to preg_match it any other way, feel free to improve this ! 

$pattern2 = '/contentpagetitle/'; 
$replacement2 ='fancybox fancybox.iframe'; 
$replacedHrefHtml2 = preg_replace($pattern2, $replacement2,$replacedHrefHtml); 
// replacement 2 
// replace the joomla class on the links with the class contentpagetitle to my fancybox  class ! fancy innit! 


$pattern2 = '/readon/'; 
$replacement2 ='fancybox fancybox.iframe'; 
$replacedHrefHtml2 = preg_replace($pattern2, $replacement2,$replacedHrefHtml); 
// replacement 2 
// replace the joomla class on the links with class readon to my fancybox class ! fancy innit! 

$replacedHrefHtml3 = preg_replace("/<img[^>]+\>/i", "<br />(Plaatje)<br /><br /> ",   $replacedHrefHtml2); 
// finally remove the images from the string ! 


$replacedHrefHtml4 = base64_encode($replacedHrefHtml3); 
// encode the html with base64 before store to mysel 
// real escape wont work since it will break the links ! 

try { 
$conn = new PDO($link, $pdo_username, $pdo_password); 
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 

$data222 = $conn->query('SELECT * FROM svvnieuws ORDER BY id DESC LIMIT 1'); 

foreach($data222 as $row) { 

$lastitem = sprintf($row[inhoud]); 

    } 
} catch(PDOException $e) { 
echo 'ERROR: ' . $e->getMessage(); 
}       
// get the last stored item in db for comparisation to current result! 

if ($replacedHrefHtml4 == $lastitem){ 
// if the last item from the db is the same, do not store a new item ! importand to prevent clutter ! 

} 
else { 
// if its not the same, store a new item ! 

$conn = new PDO($link, $pdo_username, $pdo_password); 
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
// set up the connection to the db 

$sql='INSERT INTO svvnieuws (id,inhoud) VALUES ("","'.$replacedHrefHtml4.'")'; 
// set the mysql query string 

$rip = $conn->prepare($sql); 
$rip->execute(array(':id'=>$id, 
       ':inhoud'=>$replacedHrefHtml4 
      )); 
// insert to the db ! 

} 
// close the else ! 

// place this file outside of the docroot, and let the cron run it every say 4 hours. 
// ofcourse make sure you also place dom.php in the same directory! 
// dom.php is my short name for php simple html dom. 

Так заменить 1 заменяет < A HREF = "whatver"> для < A HREF = "www.remotesite.com">
заменить 2 заменяет класс на этой HREF в FancyBox заменить 3 Заменяет класс по ссылке readon к fancybox по сравнению с последним сохраненным товаром , если в другом магазине.

Мне очень хотелось бы выяснить, как исправить неработающие ссылки, а не заменять их. Ссылки с сайта приведены в источнике как указано ниже: < a href = "/ index.php? Blabla"> Как, если бы у меня было бы возможность внедрить www.mysite.com в < a href = "/ index .php? блабла "> Это < A HREF =" www.remotesite.com/index.php?blabla ">

+0

Любые советы о том, как вводить basehref, будут оценены! – defiancenl

+0

Нашел ответ в другой теме на Stack! – defiancenl

0
include_once('db_connect.php'); 
// connect to my db 
require_once('Net/URL2.php'); 
include_once('dom.php'); 
// include html_simple_dom! 

$dom = file_get_html('http://www.targetsite.com'); 
// get the html content of a site and pass it through html simple dom ! 

$elem2 = $dom->find('div[class=blog]', 0); 
// set the div to target for ! 


$uri = new Net_URL2('http://www.svvenray.nl'); // URI of the resource 
$baseURI = $uri; 
foreach ($elem2->find('base[href]') as $elem) { 
$baseURI = $uri->resolve($elem->href); 
} 

foreach ($elem2->find('*[src]') as $elem) { 
$elem->src = $baseURI->resolve($elem->src)->__toString(); 
} 
foreach ($elem2->find('*[href]') as $elem) { 
if (strtoupper($elem->tag) === 'BASE') continue; 
$elem->href = $baseURI->resolve($elem->href)->__toString(); 
} 

echo $elem2; 

Это позволит устранить все неработающие ссылки и требует PHP PEAR Net/URL2.php