[英]issue using file_get_contents with a variable as the link to target file
我正在嘗試遍歷一系列鏈接,並使用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
條件為false。 然而,當我在file_get_contents
(`file_get_contents(“http://www.site.com/something”)中使用my_site2.txt中的一個鏈接時,它可以正常工作。
我甚至嘗試使用另一個只包含一個鏈接的txt文件,該鏈接在源代碼中具有正確的字符串。
我也試過沒有引號: file_get_contents($link)
有幾件事情。
$f
文件名將包含換行符。 您需要為file
添加其他標志以防止這種情況:
$links = file('mysite2.txt', FILE_IGNORE_NEW_LINES);
你不需要在正則表達式中轉義雙引號。
你確定你的正則表達式在/>
之前需要一個空格嗎? 你的正則表達式將匹配<meta pro="test" />
但不符合<meta pro="test"/>
。
在foreach循環中進行decalred時$ link的內容可能是一個數組或一個對象。
在$ link上嘗試var_dump()並查看其中的內容,這可能有助於您了解如何操作它的內容。
你是怎么設置.txt文件的?
這是一個解決方案: -
如果你只是像這樣的鏈接
鏈接1,鏈接2,LINK3,LINK4,link5
然后做
$links = explode( ',' , file_get_content($file) ) ;
然后foreach這個數組
只需從$f = file_get_contents("$link");
刪除引號$f = file_get_contents("$link");
使$f = file_get_contents($link);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.