简单的HTML Dom - 替换相对链接

时间:2015-04-20 15:45:26

标签: php foreach

我正在使用simple_html_dom库来抓取外部网站的菜单。

这样可以正常工作,但链接都是相对的,并且返回/关于/联系,而不是mydomain.com/about/contact。

如何在循环中替换这些实例的最佳方法?例如:

$html_out = file_get_html('http://www.domain.com/'); 
if ( $html_out ) {
    foreach($html_out->find('#menu-position-wrapper') as $article) {
    echo $article;
}

谢谢!

1 个答案:

答案 0 :(得分:0)

你可以试试这个:

$html_out = file_get_html('http://www.domain.com/'); 
if ( $html_out ) {
    foreach($html_out->find('#menu-position-wrapper') as $article) {
      foreach ($article->find('a[href]') as $a) {
        $href = $a->href;
        $a->href = 'http://www.domain.com'.$href;
  }    
 }
}