【问题标题】:PHP File get contentsPHP文件获取内容
【发布时间】:2016-05-23 19:52:12
【问题描述】:

我想知道是否可以使用文件获取内容来仅获取所需页面中的特定元素。例如:仅将内容存储在<title></title> 标签内或<meta></meta> 标签内等等。如果 file_get_contents 无法实现,我可以用什么来实现?

谢谢!

【问题讨论】:

    标签: php file-get-contents


    【解决方案1】:

    你可以使用explode()函数;

    $content = file_get_contents("http://www.demo.com");
    $explodedContent = explode("<title>", $content);
    $explodedExplodedContent = explode("</title>", $explodedContent[1]);
    
    echo $explodedExplodedContent[0]; // title of that page.
    

    你可以把它变成一个函数;

    function contentBetween($beginStr, $endStr, $contentURL){
      $content = file_get_contents($contentURL);
      $explodedContent = explode($beginStr, $content);
      $explodedExplodedContent = explode($endStr, $explodedContent[1]);
    
      return $explodedExplodedContent[0];
    }
    
    echo contentBetween("<title>", "</title>", "http://www.demo.com"); // usage.
    

    查看更多关于explode()的信息:http://php.net/manual/tr/function.explode.php

    【讨论】:

    • 跳出框框的聪明思考,我喜欢!
    • 我同意!这太棒了,它也有效!我只有一个问题——当我执行以下操作时,它并没有真正返回我要匹配的字符串的计数:echo substr_count($explodedExplodedContent[0], 'Solving'); 我得到的是 '21',而不是预期的 '1'
    • 这很奇怪,你能分享完整的代码还是作为一个新问题提出并在这里链接它?
    猜你喜欢
    • 2010-11-25
    • 1970-01-01
    • 2013-03-02
    • 2015-10-01
    • 2016-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-19
    相关资源
    最近更新 更多