dongpian2559 2014-05-21 18:51
浏览 28
已采纳

使用简单的html dom 1.5 2014 php获取元数据

I am trying to get the meta description/keywords of google.com, but I end up with a null array.

<?php
include "simple_html_dom.php";
$url = isset($_POST['url']) ? $_POST['url'] : ''; // this would be http://www.google.com
if(!empty($url) && @file_get_contents($url) == true) {
    $html = new simple_html_dom();
    $html->load_file($url); //put url or filename in place of xxx
    $title = $html->find('title', 0)->plaintext;
    //echo $title;

    $descr = $html->find("meta[name='description']", 0);
    var_dump($descr); // NULL

}
?>

the $title is being get ok, but the description is a problem and don't understand why. I also tried

$descr = $html->find("meta[name='description']", 0)->content;

results in Notice: Trying to get property of non-object

or

$descr = $html->find("meta[name='description']", 0)->attr('content');

results in Fatal error: Call to a member function attr() on a non-object

or

 $descr = $html->find("meta[name='description']", 0)->getAttribute('content');

results in Fatal error: Call to a member function getAttribute() on a non-object.

All those errors I believe that they are because meta description cannot be found, despite the fact if you turn on to view source code on Google.com you will see that is the first thing you see after head tag Please help me on this I am a noob in Simple HTML DOM. It's much appreciated.

  • 写回答

2条回答 默认 最新

  • duanchi4544 2014-05-22 23:05
    关注

    This should give you what you want:

    <?php
    include "simple_html_dom.php";
    $url = isset($_POST['url']) ? $_POST['url'] : ''; // this would be http://www.google.com
    if(!empty($url)) {
        $html = file_get_html($url);
        $title = $html->find('title', 0)->plaintext;
        echo $title . "
    ";;
    
        $descr = $html->find("meta[name='description']", 0);
        echo $descr . "
    ";
    

    } ?>

    Output is

    Google
    <meta content="Search the world's information, including webpages, images, videos and more. Google has many special features to help you find exactly what you're looking for." name="description">
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算