2015-02-10 30 views
0

這裏是我使用在這一點上的代碼無法從網頁中提取og標籤?

$file = array_rand($files); 
$filename = "http://example.com/".$files[$file]; 
echo $filename; 
libxml_use_internal_errors(true); 
$c = file_get_contents($filename); 
$d = new DomDocument(); 
$d->loadHTML($c); 
$xp = new domxpath($d); 
foreach ($xp->query("//meta[@name='og:title']") as $el) { 
echo $el->getAttribute("content"); 
} 
foreach ($xp->query("//meta[@name='og:image']") as $el) { 
echo $el->getAttribute("content"); 
} 

$ filename的URL的正確值,但它並沒有呼應OG的內容:圖片和og:標題?

編輯

這是我的網頁的典型組織

<?php require_once("headertop.php")?> 
<meta property="og:image" content="url" /> 
<meta property="og:title" content="content here." /> 
<meta property="og:description" content="description here." /> 
<title>Page title</title> 
<?php require_once("headerbottom.php")?> 

EDIT 2

From one answer I understood this. I have to use 

$rootNamespace = $d->lookupNamespaceUri($d->namespaceURI); 
$xpath->registerNamespace('og', $rootNamespace); 

然後用

<meta property="og:image" content="url" /> 

我對不對?

+0

這可能是有用的,看看輸入文件的內容。 – RiggsFolly 2015-02-10 17:58:58

回答

0

'og'是一個命名空間,所以它不會以這種方式拉動。你需要定義一個命名空間爲您的DOMXPath對象:

http://php.net/manual/en/domxpath.registernamespace.php

編輯:這是我扔在一起使用VICE主頁的例子。我從他們的開發人員網站上提取了Facebook OpenGraph XML命名空間。

<?php                    
error_reporting(E_ERROR); 
$html = file_get_contents("http://www.vice.com/"); 
$doc = new DomDocument(); 
$doc->loadHTML($html); 
$xp = new DOMXPath($doc); 
$xp->registerNamespace('og', 'http://ogp.me/ns#'); 
print_r($xp->query("//meta[@name='og:title']")->item(0)->getAttribute('content')); 
+0

我正在編輯我的問題,請看看並告訴我,如果我做對了。 – 2015-02-10 18:08:13

+0

您沒有在示例頁面中粘貼'og'的定義。它可能在某處......在'headertop.php'中? – haliphax 2015-02-10 18:09:20

+0

嘿託德,我編輯的問題,包括我認爲我需要補充的代碼,我是正確的? – 2015-02-10 18:12:35

0

這應該只是罰款:

<?php 
$html = new DOMDocument(); 
@$html->loadHTML(file_get_contents('http://www.imdb.com/title/tt0117500/')); 

foreach($html->getElementsByTagName('meta') as $meta) { 
    if(strpos($meta->getAttribute('property'), 'og') !==false) { 
     echo $meta->getAttribute('content') . '<br/>'; 
    } 
} 
?> 
+0

它沒有給出任何輸出 – 2015-02-10 18:27:10

+0

它當然對我來說。 – 2015-02-10 18:36:21