查找并替换Curl输出PHP

时间:2018-10-23 14:47:55

标签: php regex curl explode

我有两个网站。我想卷曲到网站#1上的页面,以检索包含指向我最喜欢的抽搐流的链接的html代码,并使用其api嵌入到我的页面中。使用此curl输出,我想查找并替换我的网站#1的迭代并将其替换为mywebsite#2。

即,卷曲到mywebsite1.com/myfavoritestreams>检索“ mywebsite1.com/stream1”

我想查找,替换并显示“ mywebsite2.com/stream1”。

using this stackoverflow questions as a guide我尝试了这种变化,但没有成功。只是错误消息,它要求有效的字符串和路径。

感谢所有帮助。

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "http://www.mywebsite1.com/myfavoritestreams");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");


$headers = array();
$headers[] = "Host: www.wiz1.net";
$headers[] = "Connection: keep-alive";
$headers[] = "Upgrade-Insecure-Requests: 1";
$headers[] = "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36";
$headers[] = "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8";
$headers[] = "Referer: http://www.mywebsite1.com";
$headers[] = "Accept-Encoding: gzip, deflate";
$headers[] = "Accept-Language: en-US,en;q=0.9";
$headers[] = "Cookie: __cfduid=d00d780044d6524dab736999f38359bba1534699518; _ga=GA1.2.1974576514.1534699525; _gid=GA1.2.795232845.1540262479";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$filename = curl_exec($ch);
if (curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);
}
curl_close ($ch);
$string_to_replace="mywebsite1";
$replace_with="mywebsite2";
replace_string_in_file($filename, $string_to_replace, $replace_with);

function replace_string_in_file($filename, $string_to_replace, $replace_with){
    $content=file_get_contents($filename);
    $content_chunks=explode($string_to_replace, $content);
    $content=implode($replace_with, $content_chunks);
    file_put_contents($filename, $content);
}

1 个答案:

答案 0 :(得分:2)

好,所以我认为您不能使用curl响应主体作为文件名。 您可以执行以下操作。

$body = curl_exec($ch);
$output = str_replace($string_to_replace,$replace_with,$body);
$filename = "/tmp/temp.txt" // here you need to put a valid path to a file
$file = fopen($filename,'w+');
fwrite($file,$body);
fclose($file);