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

この悪いテキスト出力に追加される可能性があると言っているので、次のコードのようなものを使用できます(コーディングを容易にするために関数でラップします)。

<?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 に答える
1

preg_replace ()を使用して、「#」で始まるすべての行を削除できます。次に例を示します。

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

あるいは単に

'/#endofscript$/'

最後にthingieと一致します。

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 に答える
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 に答える