2011-12-20 7 views
0

북마크릿에서 작업 중이며 HTML DOM 파서를 사용하여 외부 페이지의 모든 사진을 가져옵니다. 사진을 올바르게 가져 와서 내 북마크 팝업에 표시하고 있습니다. 그러나 사진의 상대 경로에 문제가 있습니다.외부 웹 페이지 이미지의 절대 경로 얻기

예를 들어 외부 페이지에 사진 소스 http://www.example.com/dir/index.php

  1. 사진 소스 1 말 : IMG 소스 = '호스트 이름/사진/photo.jpg를'- 얻기 사진이 절대적으로

  2. 사진 출처 2 : img source = '/ photos/photo.jpg'- 사진이 절대적이지는 않습니다.

현재 url을 통해 작업했는데 현재 URL로 디렉토리를 가져 오기 위해 dirname 또는 pathinfo를 사용했습니다. host/dir/(상위 디렉토리로 호스트 지정) 및 host/dir/index.php (올바른 상위 디렉토리로 host/dir) 사이에 문제가 있음

제발 도와주세요. 어떻게 상대 사진을 얻을 수 있습니까 ??

+0

그 '링크'는 무엇입니까? 제 말은 '/photo/xdfa.jpg'는 도메인 주소에서만 생각할 수 있습니다. './path/pics.jpg'도 시도해 볼 수 있습니다. 그것은 나를 위해 일했습니다 – Kris

+0

그래서 무엇이 문제입니까? 문자열이'http : //'또는'/'로 시작하는지 여부를 감지하는 방법? – Gordon

답변

5

FIXED (쿼리 문자열에 대한 지원이 추가 전용 이미지 경로)

function make_absolute_path ($baseUrl, $relativePath) { 

    // Parse URLs, return FALSE on failure 
    if ((!$baseParts = parse_url($baseUrl)) || (!$pathParts = parse_url($relativePath))) { 
     return FALSE; 
    } 

    // Work-around for pre- 5.4.7 bug in parse_url() for relative protocols 
    if (empty($baseParts['host']) && !empty($baseParts['path']) && substr($baseParts['path'], 0, 2) === '//') { 
     $parts = explode('/', ltrim($baseParts['path'], '/')); 
     $baseParts['host'] = array_shift($parts); 
     $baseParts['path'] = '/'.implode('/', $parts); 
    } 
    if (empty($pathParts['host']) && !empty($pathParts['path']) && substr($pathParts['path'], 0, 2) === '//') { 
     $parts = explode('/', ltrim($pathParts['path'], '/')); 
     $pathParts['host'] = array_shift($parts); 
     $pathParts['path'] = '/'.implode('/', $parts); 
    } 

    // Relative path has a host component, just return it 
    if (!empty($pathParts['host'])) { 
     return $relativePath; 
    } 

    // Normalise base URL (fill in missing info) 
    // If base URL doesn't have a host component return error 
    if (empty($baseParts['host'])) { 
     return FALSE; 
    } 
    if (empty($baseParts['path'])) { 
     $baseParts['path'] = '/'; 
    } 
    if (empty($baseParts['scheme'])) { 
     $baseParts['scheme'] = 'http'; 
    } 

    // Start constructing return value 
    $result = $baseParts['scheme'].'://'; 

    // Add username/password if any 
    if (!empty($baseParts['user'])) { 
     $result .= $baseParts['user']; 
     if (!empty($baseParts['pass'])) { 
      $result .= ":{$baseParts['pass']}"; 
     } 
     $result .= '@'; 
    } 

    // Add host/port 
    $result .= !empty($baseParts['port']) ? "{$baseParts['host']}:{$baseParts['port']}" : $baseParts['host']; 

    // Inspect relative path path 
    if ($relativePath[0] === '/') { 

     // Leading/means from root 
     $result .= $relativePath; 

    } else if ($relativePath[0] === '?') { 

     // Leading ? means query the existing URL 
     $result .= $baseParts['path'].$relativePath; 

    } else { 

     // Get the current working directory 
     $resultPath = rtrim(substr($baseParts['path'], -1) === '/' ? trim($baseParts['path']) : str_replace('\\', '/', dirname(trim($baseParts['path']))), '/'); 

     // Split the image path into components and loop them 
     foreach (explode('/', $relativePath) as $pathComponent) { 
      switch ($pathComponent) { 
       case '': case '.': 
        // a single dot means "this directory" and can be skipped 
        // an empty space is a mistake on somebodies part, and can also be skipped 
        break; 
       case '..': 
        // a double dot means "up a directory" 
        $resultPath = rtrim(str_replace('\\', '/', dirname($resultPath)), '/'); 
        break; 
       default: 
        // anything else can be added to the path 
        $resultPath .= "/$pathComponent"; 
        break; 
      } 
     } 

     // Add path to result 
     $result .= $resultPath; 

    } 

    return $result; 

} 

테스트 :

echo make_absolute_path('http://www.example.com/dir/index.php','/photos/photo.jpg')."\n"; 
// Outputs: http://www.example.com/photos/photo.jpg 
echo make_absolute_path('http://www.example.com/dir/index.php','photos/photo.jpg')."\n"; 
// Outputs: http://www.example.com/dir/photos/photo.jpg 
echo make_absolute_path('http://www.example.com/dir/index.php','./photos/photo.jpg')."\n"; 
// Outputs: http://www.example.com/dir/photos/photo.jpg 
echo make_absolute_path('http://www.example.com/dir/index.php','../photos/photo.jpg')."\n"; 
// Outputs: http://www.example.com/photos/photo.jpg 
echo make_absolute_path('http://www.example.com/dir/index.php','http://www.yyy.com/photos/photo.jpg')."\n"; 
// Outputs: http://www.yyy.com/photos/photo.jpg 
echo make_absolute_path('http://www.example.com/dir/index.php','?query=something')."\n"; 
// Outputs: http://www.example.com/dir/index.php?query=something 

난 그 올바르게 발생하는 모든 걸에 대한 당신의 가능성에 대처해야한다고 생각하고, 브라우저에서 사용하는 로직과 대략 동일해야합니다. 또한 유령 슬래시가있는 dirname()을 사용하여 Windows에서 발생할 수있는 이상한 점을 수정해야합니다.

첫 번째 인수는 당신이 <img> (또는 <a> 또는 무엇이든)을 발견 페이지와 두 번째 인수의 전체 URL입니다 src/href 등 속성의 내용입니다.

누군가가 작동하지 않는 것을 발견하면 (나는 당신이 모든 것을 깨뜨릴 것임을 알고 있으므로 :-D), 알려 주시면 해결하겠습니다.

+1

간단한 단어 : AWESOMEEEEEE – Rohit

+0

@Rohit 방금 몇 가지 작은 수정을 추가했습니다 :-) – DaveRandom

0

'/'는 기본 경로 여야합니다. dom 파서에서 반환 된 첫 번째 문자를 확인하고 '/'이면 도메인 이름 앞에 접두어를 붙입니다.

+0

감사합니다. 메인 웹 사이트가 www.yahoo.com/news/ ...와 같은 하위 디렉토리 인 경우에 대해 알려주십시오. www.yahoo.com을 도메인 이름으로 반환합니다. 따라서 이미지 경로 검출은 실패 할 것이다. – Rohit

+0

일반적으로 전체 기본 경로 + 이미지 경로 (제공된 # 1 예와 같이)를 사용해야합니다. img src가 '/'로 시작하는 경우에만 첫 번째 슬래시 뒤의 전체 경로 빼기를 사용해야합니다. 그래서 www.yahoo.com/finance/AAPL => www.yahoo.com에 img src : '/photos/photo.jpg'를 추가하십시오. DOM 파서는 어떤 언어로 쓰여 있습니까? –