2011-05-05 40 views
6

嘿家伙,我很难形象化和构思去刮这个页面:http://www.morewords.com/ends-with/aw的话本身。给定一个URL,我想获得的内容,然后生成一个PHP阵列的所有单词上市,这在源模样刮通配符和php

<a href="/word/word1/">word1</a><br /> 
<a href="/word/word2/">word2</a><br /> 
<a href="/word/word3/">word3</a><br /> 
<a href="/word/word4/">word4</a><br /> 

有几个方法,我一直在想这样做,如果您能帮助我确定最有效的方式,我将不胜感激。此外,我会很感激任何建议或例子如何实现这一点。我知道这不是非常复杂,但我可以使用高级黑客的帮助。

  • 通过使用某种形式的jQuery $。每()的循环,不知何故他们区分到一个JS数组,然后抄写(可能重税)
  • 使用某种卷曲的(真的没有很多经验与卷曲)
  • 使用一些复杂的查找和替换正则表达式。

回答

3

你标记它作为PHP,所以这里是一个PHP的解决方案:)

$dom = new DOMDocument; 

$dom->loadHTMLFile('http://www.morewords.com/ends-with/aw'); 

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

$words = array(); 

foreach($anchors as $anchor) { 
    if ($anchor->hasAttribute('href') AND preg_match('~/word/\w+/~', $anchor->getAttribute('href'))) { 
     $words[] = $anchor->nodeValue; 
    } 
} 

CodePad

如果在php.ini中禁用了allow_url_fopen,则可以使用cURL来获取HTML。

$curl = curl_init(); 
curl_setopt($curl, CURLOPT_URL, 'http://www.morewords.com/ends-with/aw'); 
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); 
$html = curl_exec($curl);  
curl_close($curl); 
+0

它确实看起来应该起作用,在你的例子中,它的确如此!但是,由于某种原因,它不在我的主机上:http://go.phpfogapp.com/这里是代码:http://gist.github.com/da32674c011d51503453 – willium 2011-05-06 00:00:17

+0

@willum要打开这样的URL,你可能在'php.ini'中需要'allow_url_fopen'。如果禁用了它,可以使用cURL库将HTML传递给'DOMDocument'。 – alex 2011-05-06 00:01:57

+0

也,如果可能的话,我很乐意用PHP解决方案。 – willium 2011-05-06 00:03:52