2014-10-19 16:38
浏览 37


I'm using cURL to fetch META Description of a web page. Here's the fraction of the code:

   $metas = $doc->getElementsByTagName('meta');

   for ($i = 0; $i < $metas->length; $i++)
        $meta = $metas->item($i);
        $metaname = $meta->getAttribute('name');
        if($metaname == 'description')
              $description = $meta->getAttribute('content');
    <META name="description" content="<?php echo $description; ?>" />

It works ok, but not perfectly. The problem happens when the character case of an element's attribute or value is different from what was defined. For example, the code above would not output the content values if the META attribute "name" or its value "description" is uppercase(NAME,DESCRIPTION) or capitalized(Name,Description).

How do I work around this without too much codes?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • douliang6563
    douliang6563 2014-10-19 16:44

    You can also try php's strcasecmp()


    if (strcasecmp($metaname, 'description') == 0) {

    And, according to this SO answer, strcasecmp() and strtolower() approaches are o(n) in speed however using strtolower() allocates a new string to hold the result which in turn increases memory pressure and reduces performance

    PHP Doc

    点赞 评论
  • dpnvrt3119
    dpnvrt3119 2014-10-19 16:43

    You can use strtolower to make all characters small case of $metaname
    Modify your IF-condition to the following

    if(strtolower($metaname) == 'description')
    $description = $meta->getAttribute('content');
    点赞 评论