简体   繁体   中英

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.

I know I can use get_meta_tags('single_URL'); , but i need to get the metas from the URL on submit :

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 .

Assuming you are using 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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