php如何从外部url获得元标签,而无需重新加载页面


how to php get meta tag from external url Without reload page

我的页面上有很多输入,比如

user name
URL
Des
keywords
bl bl

我需要从用户在使用JavaScript或Ajax的URL输入中输入的URL中获取元标记因为我不需要重新加载页面

我知道我可以使用get_meta_tags('single_URL');,但我需要从提交时的URL获取元数据:

下面是我的代码:

function file_get_contents_curl($url)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    $data = curl_exec($ch);
    curl_close($ch);
    return $data;
}
$html = file_get_contents_curl("http://example.com/");
//parsing begins here:
$doc = new DOMDocument();
@$doc->loadHTML($html);
$nodes = $doc->getElementsByTagName('title');
//get and display what you need:
$title = $nodes->item(0)->nodeValue;
$metas = $doc->getElementsByTagName('meta');
for ($i = 0; $i < $metas->length; $i++)
{
    $meta = $metas->item($i);
    if($meta->getAttribute('name') == 'description')
        $description = $meta->getAttribute('content');
    if($meta->getAttribute('name') == 'keywords')
        $keywords = $meta->getAttribute('content');
}
echo "Title: $title". '<br/><br/>';
echo "Description: $description". '<br/><br/>';
echo "Keywords: $keywords";

我会这样称呼它:

$html = file_get_contents_curl("http://example.com/"); //<< I need to set the url with the user input without reloading the page

您正在寻找的是所谓的xhr, XMLHttpRequest或更常见的:AJAX

假设你正在使用JQuery:

客户端:
<script>
function get_metas(){
    url = $('#txt_url').val();
    $('#result').load('your_script.php?url=' + encodeURIComponent(url));
}
</script>
<form id='search' method='post' onsubmit='get_metas();return false;'>
<input type='text' id='txt_url' name='url'/>
<input type='submit' value='OK'>
</form>
<div id='result'></div>

服务器端:

...
$html = file_get_contents_curl($_GET['url']);
...

要小心,因为这可能会把你的服务器变成一个代理来做不好的事情。