【问题标题】:URL Search for a string with file_get_contentsURL 使用 file_get_contents 搜索字符串
【发布时间】:2014-07-22 16:14:57
【问题描述】:

我正在编写一个 php 脚本,它在 url (http://mp3skull.com/) 中搜索文本“.mp3”,希望将下载链接打印为字符串。下面是我到目前为止的代码,它在 mp3skull 页面的 html 代码中搜索“.mp3”,并在成功时通知用户。我需要帮助的部分:脚本需要能够在网页源中找到“.mp3”,然后将源代码中位于它之前的 url/文本打印为纯文本字符串。我希望这是有道理的,你能够帮助我。谢谢。

<?php
$filename = 'http://mp3skull.com/mp3/hot_mallets.html';
$searchfor = '.mp3';
$file = file_get_contents($filename);
if(strpos($file, $searchfor)) 
{
   echo "String found";
}
?>

【问题讨论】:

  • 我对你想要达到的目标有一种感觉,虽然我不知道该怎么做,但是在使用&lt;!DOCTYPE html&gt;&lt;head&gt;&lt;/head&gt;&lt;body&gt;Hello world &lt;a href="link.xxx"&gt;file.mp3&lt;/a&gt;&lt;/body&gt;&lt;/html&gt; 时,echo "$file"; 确实输出了Hello world file.mp3如果这就是你想要得到的。

标签: php url search download


【解决方案1】:

试试这个

<?php
$filename = 'http://mp3skull.com/mp3/hot_mallets.html';
$searchfor = '.mp3';
$file = file_get_contents($filename);
$html = new DOMDocument();
@$html->loadHTML($file);
foreach($html->getElementsByTagName('a') as $a) {
    $property=$a->getAttribute('href');
    if (strpos($property , $searchfor))
        print_r($property);             
            echo "<br/><br/>";
}
?>

【讨论】:

    【解决方案2】:

    您为该工作使用了错误的工具。要有效地获得这些值,请改用DOMDocument + DOMXpath。示例:

    $contents = file_get_contents('http://mp3skull.com/mp3/hot_mallets.html');
    $dom = new DOMDocument();
    libxml_use_internal_errors(true);
    $dom->loadHTML($contents);
    libxml_clear_errors();
    $xpath = new DOMXpath($dom);
    
    $element = $xpath->query('//div[@id="right_song"]/div[3]/div[1]/div[1]/a')->item(0)->getAttribute('href');
    echo $element; //http://incoming.jazz-on-line.com/a/mp3a/VIC041408.mp3
    

    【讨论】:

      猜你喜欢
      • 2014-04-12
      • 1970-01-01
      • 1970-01-01
      • 2020-03-19
      • 1970-01-01
      • 2016-05-03
      • 2011-04-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多