PHP: Get DOM attribute with encoding preserved

905

I'm currently parsing some tags in an HTML document using PHP DOM. I want to get the value of the content attribute value of the "keywords" meta tag UNCHANGED.

For an example, the string "keyword1, keyword2, keyword2, keyword3" returns "keyword1, keyword2, keyword2, keyword3", and therefore, breaks the real amount of keywords in the output XML Document.

I have already tried using "htmlentities()", but it didn't do anything.

900

Answer

Solution:

I know this is late, but after I revisited my code to make some edits, I found the solution via regex.

function GetMetaTagsContentIntact($html, $meta_name)
{
    $get_attribute_value = function($attrib, $tag)
    {
        //get attribute from html tag
        $re = '/' . preg_quote($attrib) . '=([\'"])?((?(1).+?|[^\s>]+))(?(1)\1)/is';
        if (preg_match($re, $tag, $match))
        {
          return urldecode($match[2]);
        }
        return false;
    };

    $output; // Get all meta tags.
    preg_match_all("|<meta[^>]+name=\"([^\"]*)\"[^>]" . "+content=\"([^\"]*)\"?[^>]+>|i", $html, $output, PREG_PATTERN_ORDER);
    $output = $output[0];
    // Get specified mata tag's content value.
    foreach($output as $tag)
    {
        if($meta_name == trim($get_attribute_value("name", $tag)))
        {
            return $get_attribute_value("content", $tag);
        }
    }

    return false;
}

This takes the raw HTML (preferably parsed), and uses regex to get the meta tag itself, then from that, extracts the content value from the meta tag you want.

However, to append the data successfully to say, an XML document as I was, you need to use "textContent" specifically. More on that here: PHP: DOMNode - Manual

People are also looking for solutions to the problem: php - Add fee based on specific cart total in WooCommerce

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.