简体   繁体   English

如何通过PHP从外部URL获取元标记而无需重新加载页面

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

I have many inputs on my page like 我的页面上有很多输入,例如

user name
URL
Des
keywords
bl bl

I need to get the meta tags from an URL the user enters in the URL input with JavaScript or Ajax because I need not to reload the page. 我需要从用户使用JavaScript或Ajax输入URL输入的URL获取元标记,因为我不需要重新加载页面。

I know I can use get_meta_tags('single_URL'); 我知道我可以使用get_meta_tags('single_URL'); , but i need to get the metas from the URL on submit : ,但我需要从Submit上的URL获取metas:

Here's my code : 这是我的代码:

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";

I would call it as such : 我这样称呼它:

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

What you are looking for is called xhr , XMLHttpRequest or more commonly : AJAX . 您正在寻找的是xhrXMLHttpRequest或更常见的名称: AJAX

Assuming you are using JQuery : 假设您正在使用JQuery:

Client side : 客户端 :

<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>

Server side : 服务器端 :

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

Be careful though as this can potentially turn your server into a proxy to do bad things. 但是请务必小心,因为这有可能将您的服务器变成代理来执行不良操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM