2010-12-12 6 views
21

per il mio sito Web, vorrei aggiungere una nuova funzionalità.come estrarre link e titoli da una pagina .html?

vorrei utente sia in grado di caricare il suo file di segnalibri di backup (da qualsiasi browser, se possibile) in modo da poter caricare su loro profilo e che non c'è bisogno di inserire manualmente tutti loro ...

l'unica parte che mi manca per fare questo è la parte di estrarre titolo e URL dal file caricato .. qualcuno può dare un indizio su dove iniziare o dove leggere?

opzione di ricerca utilizzata e (how to extract data from a raw html file) questo sis la più correlata domanda per la mia e non parlarne ..

Io davvero non importa se utilizza jQuery o PHP

ringraziamento molto

+1

sarebbe probabilmente aiutare tutti se si potesse mettere esempi dei tipi di file di backup dei segnalibri che desideri sostenere (per ogni browser) – scoates

+1

Il formato di Netscape è comune: http://msdn.microsoft.com/en-us/library/aa753582(v=vs.85).aspx – Matthew

risposta

43

Grazie a tutti, ho capito!

il codice finale: Questo ti mostra la ancoraggio testo assegnato e la href per tutti i link in un file .html

$html = file_get_contents('bookmarks.html'); 
//Create a new DOM document 
$dom = new DOMDocument; 

//Parse the HTML. The @ is used to suppress any parsing errors 
//that will be thrown if the $html string isn't valid XHTML. 
@$dom->loadHTML($html); 

//Get all links. You could also use any other tag name here, 
//like 'img' or 'table', to extract other tags. 
$links = $dom->getElementsByTagName('a'); 

//Iterate over the extracted links and display their URLs 
foreach ($links as $link){ 
    //Extract and show the "href" attribute. 
    echo $link->nodeValue; 
    echo $link->getAttribute('href'), '<br>'; 
} 

Ancora una volta, grazie mille.

30

Questo è probabilmente sufficiente:

$dom = new DOMDocument; 
$dom->loadHTML($html); 
foreach ($dom->getElementsByTagName('a') as $node) 
{ 
    echo $node->nodeValue.': '.$node->getAttribute("href")."\n"; 
} 
+2

whre $ html è il percorso del file? Grazie per una risposta così rapida: D –

+2

@Toni, '$ html' è la stringa che contiene l'HTML. Puoi usare '$ dom-> loadHTMLFile()' per caricare direttamente da un file. (Si consiglia di aggiungere un prefisso con '@' per sopprimere gli avvertimenti.) – Matthew

+0

wow! Grazie mille! sembra quasi finito! Posso ottenere collegamenti ma ho problemi con nomi o titoli (ho provato entrambi) –

5

Supponendo che i link memorizzati sono in un file HTML la soluzione migliore è probabilmente t o usa un parser html come PHP Simple HTML DOM Parser (mai provato da solo). (L'altra opzione è quella di cercare usando la ricerca delle stringhe di base o regexp, e dovresti probabilmente mai usare regexp per analizzare html).

Dopo aver letto il file html utilizzando l'uso parser le sue funzioni per trovare le a tag:

dal tutorial:

// Find all links 
foreach($html->find('a') as $element) 
     echo $element->href . '<br>'; 
3

questo è un esempio, è possibile utilizzare nel vostro caso questo:

$content = file_get_contents('bookmarks.html'); 

Esegui questo:

<?php 

$content = '<html> 

<title>Random Website I am Crawling</title> 

<body> 

Click <a href="http://clicklink.com">here</a> for foobar 

Another site is http://foobar.com 

</body> 

</html>'; 

$regex = "((https?|ftp)\:\/\/)?"; // SCHEME 
$regex .= "([a-z0-9+!*(),;?&=\$_.-]+(\:[a-z0-9+!*(),;?&=\$_.-]+)[email protected])?"; // User and Pass 
$regex .= "([a-z0-9-.]*)\.([a-z]{2,4})"; // Host or IP 
$regex .= "(\:[0-9]{2,5})?"; // Port 
$regex .= "(\/([a-z0-9+\$_-]\.?)+)*\/?"; // Path 
$regex .= "(\?[a-z+&\$_.-][a-z0-9;:@&%=+\/\$_.-]*)?"; // GET Query 
$regex .= "(#[a-z_.-][a-z0-9+\$_.-]*)?"; // Anchor 


$matches = array(); //create array 
$pattern = "/$regex/"; 

preg_match_all($pattern, $content, $matches); 

print_r(array_values(array_unique($matches[0]))); 
echo "<br><br>"; 
echo implode("<br>", array_values(array_unique($matches[0]))); 

uscita:

Array 
(
    [0] => http://clicklink.com 
    [1] => http://foobar.com 
) 

http://clicklink.com

http://foobar.com

1
$html = file_get_contents('your file path'); 

$dom = new DOMDocument; 

@$dom->loadHTML($html); 

$styles = $dom->getElementsByTagName('link'); 

$links = $dom->getElementsByTagName('a'); 

$scripts = $dom->getElementsByTagName('script'); 

foreach($styles as $style) 
{ 

    if($style->getAttribute('href')!="#") 

    { 
     echo $style->getAttribute('href'); 
     echo'<br>'; 
    } 
} 

foreach ($links as $link){ 

    if($link->getAttribute('href')!="#") 
    { 
     echo $link->getAttribute('href'); 
     echo'<br>'; 
    } 
} 

foreach($scripts as $script) 
{ 

     echo $script->getAttribute('src'); 
     echo'<br>'; 

} 
+0

Styling non riuscito e la risposta è difficile da leggere. Modifica la tua risposta e rendila più leggibile – michaldo

+1

Troppo codice per la domanda data ... –