【问题标题】:issue using file_get_contents with a variable as the link to target file使用带有变量的 file_get_contents 作为目标文件的链接的问题
【发布时间】:2011-12-01 15:56:01
【问题描述】:

我正在尝试遍历链接数组,并使用 file_get_contents 获取源代码并从中获取某些内容:

$links = file('mysite2.txt');

foreach($links as $link) {

$f = file_get_contents("$link");
$source = $f;


if(preg_match('/<meta pro=\"(.*)\" \/>/',$source,$matches)) {
   $answer = $matches[1];

echo "$answer";
}

}

现在,当我在 file_get_contents (file_get_contents("$link")) 函数中使用 $link 时,preg_match 条件为假。然而,当我在file_get_contents (`file_get_contents("http://www.site.com/something")) 中使用 my_site2.txt 中的链接之一时,它可以正常工作。

我什至尝试过使用仅包含一个链接的不同 txt 文件,该链接在源代码中具有正确的字符串。

我也试过不带引号:file_get_contents($link)

【问题讨论】:

    标签: php file-get-contents


    【解决方案1】:

    有几件事。

    1. $f 中的文件名将包含换行符。您需要为 file 添加一个额外的标志来防止这种情况:

      $links = file('mysite2.txt', FILE_IGNORE_NEW_LINES);
      
    2. 您不需要在正则表达式中转义双引号。

    3. 您确定您的正则表达式在/&gt; 之前需要一个空格吗?您的正则表达式将匹配 &lt;meta pro="test" /&gt;,但不匹配 &lt;meta pro="test"/&gt;

    【讨论】:

    • 对,我明白了。为那个伙伴干杯。
    【解决方案2】:

    在 foreach 循环中标记时 $link 的内容可能是一个数组或一个对象。

    在 $link 上尝试 var_dump() 并查看其中的内容,这可能有助于您了解如何操作它的内容。

    .txt 文件设置如何?

    这是一个解决方案:-

    如果你只是将链接分开

    链接1,链接2,链接3,链接4,链接5

    那就做吧

    $links = explode( ',' , file_get_content($file) ) ;
    

    然后foreach这个数组

    【讨论】:

      【解决方案3】:

      只需删除 $f = file_get_contents("$link"); 中的引号

      制作$f = file_get_contents($link);

      【讨论】:

        猜你喜欢
        • 2018-09-17
        • 1970-01-01
        • 2012-09-17
        • 1970-01-01
        • 1970-01-01
        • 2015-10-26
        • 1970-01-01
        • 2023-04-03
        • 1970-01-01
        相关资源
        最近更新 更多