簡體   English   中英

如何通過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'); ,但我需要從Submit上的URL獲取metas:

這是我的代碼:

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

您正在尋找的是xhrXMLHttpRequest或更常見的名稱: 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']);
...

但是請務必小心,因為這有可能將您的服務器變成代理來執行不良操作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM