Jump to content

[SOLVED] PHP and Regular Expression in html page


Jagarm

Recommended Posts

Hello everyone,

 

I am trying to extract some stuff from a page, the following is what i have so far.

 

$content = file_get_contents ( "http://www.dfo-mpo.gc.ca/media/news-presse-eng.htm" );

echo preg_match_all("/<li>(<[^\r]*?)<\/li>/", $content, $maches,PREG_SET_ORDER);
echo "<pre>";
print_r ( $maches );
echo "</pre>";

 

If you view the source on that page you will see I am trying to extract whatever is in <li> and </li> and contains a hyperlink inside <li> and </li>

 

I'm been trying so hard with no luck. I have the regex testbed that I test the regex, it works there but not with php.

 

I would appreciate for your help.

 

Thanks

Link to comment
Share on other sites

In cases where looking through tags on a site, one can use DOMDocument / xpath instead.

So if I understand you correctly, you want to only fetch <li> tags with links within them? Perhaps something along the lines of:

 

$dom = new DOMDocument;
@$dom->loadHTMLFile('http://www.dfo-mpo.gc.ca/media/news-presse-eng.htm');
$xpath = new DOMXPath($dom);
$aTag = $xpath->query('//li/a');

foreach ($aTag as $val) {
    echo 'href="' . $val->getAttribute('href') . '" - ' . $val->nodeValue . "<br />\n";
}

 

Output:

href="/media/news-presse-eng.htm" - News Releases
href="/media/charges-inculpations-eng.htm" - Charges and Convictions
href="/media/back-fiche-eng.htm" - Backgrounders
href="/media/statement-declarations-eng.htm" - Ministerial Statements
href="/media/speeches-discours-eng.htm" - Speeches
href="http://www.glf.dfo-mpo.gc.ca/comm/nr-cp/alert-avis-e.php" - E-News 
href="/media/infocus-alaune-eng.htm" - Infocus
href="/media/contacts-eng.htm" - Contacts
.
.
.
etc

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.