2012-12-10 6 views
2

PHP를 사용하여 배열에서 URL 데이터를 가져 오는 데 문제가 있습니다.PHP 배열 robots.txt의 사이트 맵 구문 분석

내 코드는 메신저는 각 사이트 맵은 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 

내가 각 루프를 작성하는 시도와 같은 주소를 표시하지만, 나는 그것을 작동시킬 수 없습니다.

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

그냥 Sitemap을 반환합니다. http://www.google.com/hostednews/sitemap_index.xmlhttp://www.google.com/hostednews/sitemap_index.xml –

+0

코드를 그대로 사용 했습니까? 내가 테스트하고 내 코드의 전체 및 각 Sitemap에 대한 URL을 반환합니다. –

+0

줄 바꿈을 추가하고
도 추가 했으므로 원하는대로 줄 바꿈을 할 수 있습니다. –

2

대신 echo $sitemap; 평가 echo $sitemap[1];

+0

감사합니다. –

+0

모든 OP가 수행해야 할 때 불필요하게 다차원 배열을 foreach() 루프에 전달할 때 비효율적 일 수 있습니다. 이는 일치하는 올바른 단일 차원 배열을 전달해야합니다. –

+0

다른 방법을 권장합니까? –