Search code examples
phpxmldom

How to ignore character case of attribute's value?


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?


Solution

  • You can also try php's strcasecmp()

    Example

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

    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