2012-12-10 25 views
2

我有一些问题试图从使用PHP的数组中获取URL数据。PHP Array解析robots.txt中的站点地图

我的代码和IM试图让每一个网站地图在robots.txt文件

$robots_file = file_get_contents($robotsTXT); 
$pattern = "/Sitemap: ([^\r\n]*)/"; 
$i = preg_match_all($pattern, $robots_file, $match, PREG_SET_ORDER); 

print_r($match); 

的print_r($比赛)中提到;下面

Array ( 
    [0] => Array ([0] => Sitemap: http://www.google.com/culturalinstitute/sitemap.xml 
    [1] => http://www.google.com/culturalinstitute/sitemap.xml) 
    [1] => Array ([0] => Sitemap: http://www.google.com/hostednews/sitemap_index.xml 
    [1] => http://www.google.com/hostednews/sitemap_index.xml) 
    [2] => Array ([0] => Sitemap: http://www.google.com/sitemaps_webmasters.xml 
    [1] => http://www.google.com/sitemaps_webmasters.xml) 
    [3] => Array ([0] => Sitemap: http://www.google.com/ventures/sitemap_ventures.xml 
    [1] => http://www.google.com/ventures/sitemap_ventures.xml) 
    [4] => Array ([0] => Sitemap: http://www.gstatic.com/dictionary/static/sitemaps/sitemap_index.xml [1] => http://www.gstatic.com/dictionary/static/sitemaps/sitemap_index.xml) 
    [5] => Array ([0] => Sitemap: http://www.gstatic.com/earth/gallery/sitemaps/sitemap.xml 
    [1] => http://www.gstatic.com/earth/gallery/sitemaps/sitemap.xml) 
    [6] => Array ([0] => Sitemap: http://www.gstatic.com/s2/sitemaps/profiles-sitemap.xml 
    [1] => http://www.gstatic.com/s2/sitemaps/profiles-sitemap.xml) 
    [7] => Array ([0] => Sitemap: http://www.gstatic.com/trends/websites/sitemaps/sitemapindex.xml 
    [1] => http://www.gstatic.com/trends/websites/sitemaps/sitemapindex.xml) 
) 

回报我想要做的是显示像这样

http://www.google.com/culturalinstitute/sitemap.xml 
http://www.google.com/hostednews/sitemap_index.xml 
http://www.google.com/sitemaps_webmasters.xml 
http://www.google.com/ventures/sitemap_ventures.xml 
http://www.gstatic.com/dictionary/static/sitemaps/sitemap_index.xml 
http://www.gstatic.com/earth/gallery/sitemaps/sitemap.xml 
http://www.gstatic.com/s2/sitemaps/profiles-sitemap.xml 
http://www.gstatic.com/trends/websites/sitemaps/sitemapindex.xml 

我试着写一个for each循环的地址,但我无法得到它的工作。

foreach($match as $sitemap){ 

echo $sitemap[1]; 

} 

任何帮助,将不胜感激

回答

3
$robots_file = file_get_contents($robotsTXT); 

$pattern = '/Sitemap: ([^\s]+)/'; 
preg_match_all($pattern, $robots_file, $match); 

print_r($match[1]); 

foreach ($match[1] as $sitemap) 
{ 
    echo $sitemap . "<br />\n"; 
} 

你不需要通过整个匹配的数组循环,只是通过它为$比赛[阵列需要循环1]。

+0

这只是返回站点地图:http://www.google.com/hostednews/sitemap_index.xmlhttp://www.google.com/hostednews/sitemap_index.xml –

+0

您是否使用代码逐字?我测试了整个代码,并返回了每个站点地图的url。 –

+0

我添加了一个换行符,并且
也是如此,所以它会在一个新行中输出它,以防您想要这样做。 –

2

,而不是echo $sitemap;尝试echo $sitemap[1];

+0

斑点钱,谢谢 –

+0

这将是低效的,因为它仍然不必要地将多维数组传递给foreach()循环,当所有OP必须做的是从匹配传递正确的单维数组。 –

+0

你是否建议采用不同的方式来做到这一点? –