从其他网站提取文本


Pull text from another website

是否可以使用php从另一个域(当前未拥有)提取文本数据?如果没有其他方法?我试过使用Iframes,因为我的页面是一个移动网站,所以看起来不太好。我想展示一个特定区域的海洋预报。这是我试图显示的链接。

更新。。。。。。。。。。。

这就是我最终使用的。也许它会帮助其他人。然而,我觉得我的问题有不止一个正确的答案。

<?php
$ch = curl_init("http://forecast.weather.gov/MapClick.php?lat=29.26034686&lon=-91.46038359&unit=0&lg=english&FcstType=text&TextType=1");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
$content = curl_exec($ch);
curl_close($ch);
echo $content;
?>

这是我想你想要的,只是它取决于天气网站的相同格式(也就是显示"Outlook")。

<?php
//define the URL of the resource
$url = 'http://forecast.weather.gov/MapClick.php?lat=29.26034686&lon=-91.46038359&unit=0&lg=english&FcstType=text&TextType=1';
//function from http://stackoverflow.com/questions/5696412/get-substring-between-two-strings-php
function getInnerSubstring($string, $boundstring, $trimit=false)
{
    $res = false;
    $bstart = strpos($string, $boundstring);
    if($bstart >= 0)
    {
        $bend = strrpos($string, $boundstring);
        if($bend >= 0 && $bend > $bstart)
        {
            $res = substr($string, $bstart+strlen($boundstring), $bend-$bstart-strlen($boundstring));
        }
    }
    return $trimit ? trim($res) : $res;
}
//if the URL is reachable
if($source = file_get_contents($url))
{
    $raw = strip_tags($source,'<hr>');
    echo '<pre>'.substr(strstr(trim(getInnerSubstring($raw,"<hr>")),'Outlook'),7).'</pre>';
}
else{
    echo 'Error';
}
?>

如果您需要任何修改,请发表意见。

尝试使用如下所示的用户代理。然后,您可以使用simplexml来解析内容并提取所需的文本。有关simplexml的更多信息。

$opts = array(
  'http'=>array(
    'method'=>"GET",
    'header'=>"User-agent: www.example.com"
  )
);
$content = file_get_contents($url, false, stream_context_create($opts));
$xml = simplexml_load_string($content);

您可以使用cURL。看看http://www.php.net/manual/en/book.curl.php