1

我正在尝试使用 cURL 从另一个 URL 获取/获取文本。我从中获取文本的位置是在具有动态(非静态)数据的空白 HTML 文档中,因此没有要过滤的 HTML 标记。这是我到目前为止所得到的:

$c = curl_init('http://url.com/dataid='.$_POST['username']);
curl_setopt(CURLOPT_RETURNTRANSFER, true);
curl_setopt(CURLOPT_FRESH_CONNECT, true);

$html = curl_exec($c);

if (curl_error($c))
die(curl_error($c));

// Get the status code
$status = curl_getinfo($c, CURLINFO_HTTP_CODE);

curl_close($c);

这完美地工作,但是在动态 HTML 文档的末尾有不需要的文本,“ #endofscript ”(不带引号)。这会被抓取/获取,那么怎么做才能不抓住它呢?我试过查看“ strpos ”等,但我不确定如何将它与 cURL 集成。

所有/任何帮助将/将不胜感激。:)

编辑:我目前使用的代码:

<?php

$homepage = file_get_contents('http://stackoverflow.com/');

$result = substr("$homepage", 0, -12);

echo $result;

?>
4

4 回答 4

2

为什么不简单地使用

<?php
$homepage = file_get_contents('http://www.example.com/');
echo $homepage;
?>

http://php.net/manual/en/function.file-get-contents.php

于 2010-06-25T18:13:05.880 回答
1

您可以使用preg_replace () 删除所有以“#”开头的行,例如:

$res = preg_replace('/^#.*$[\\r\\n]*/m','',$dat);

要不就

'/#endofscript$/'

匹配最后的东西。

substr/str_replace/其他一些字符串函数也可以。


一些示例代码如何实现 substr/preg_replace 方法:

<pre><?php

$dat = 'Lorem ipsum dolor sit amet,
        consectetur adipisicing 
        elit #endofscript';

// either
if (substr($dat,-12) == '#endofscript')
    $res = substr($dat,0,-12);

var_dump($res);

// or
$res = preg_replace('/#endofscript$/','',$dat);
var_dump($res);

?></pre>
于 2010-06-25T18:44:42.940 回答
1

由于您说此错误文本可能会附加到输出中,因此您可以使用类似以下代码的内容(将其包装在函数中以获得更轻松的编码体验):

<?php
define("bad_text", "#endofscript");

$feed_text = "here is some text#endofscript";
$bExist = false;
if(strlen($feed_text) >= constant("bad_text"))
{
    $end_of_text = substr($feed_text, strlen($feed_text) - strlen(constant("bad_text")));
    $bExist = strcmp($end_of_text, constant("bad_text")) == 0;
}

if($bExist)
    $final_text = substr($feed_text, 0, strlen($feed_text) - strlen(constant("bad_text")));
else
    $final_text = $feed_text;

echo $final_text;
?>
于 2010-06-25T18:53:44.820 回答
0

谢谢大家的帮助,我不能说我有多感激他们!使用 GOsha 提供的脚本,我设法对其进行了修改,以便删除结尾文本。使用的代码如下:

<?php

$homepage = file_get_contents('http://url.com/dataid='.$_POST['username']);

$rest = substr("$homepage", 0, -12);
echo $rest;

?>

现在已经回答了这个问题。谢谢大家,我非常感谢大家的回复。:)

于 2010-06-25T18:44:18.750 回答