Deciding between a pair of Meta Tags options

My current project involves extracting meta tags from websites and displaying the results. The code I am using has been working well, but I have encountered an issue...

This is the code snippet in question:

static private function _parse($HTML) {
    $old_libxml_error = libxml_use_internal_errors(true);

    $doc = new DOMDocument();
    $doc->loadHTML($HTML);

    libxml_use_internal_errors($old_libxml_error);

    $tags = $doc->getElementsByTagName('meta');
    if (!$tags || $tags->length === 0) {
        return false;
    }

    $page = new self();

    foreach ($tags AS $tag) {
        if ($tag->hasAttribute('property') &&
            strpos($tag->getAttribute('property'), 'og:') === 0) {
            $key = strtr(substr($tag->getAttribute('property'), 3), '-', '_');
            $page->_values[$key] = $tag->getAttribute('content');
        }
    }


    if (empty($page->_values)) { return false; }

    return $page;
}

While this code works flawlessly for URLs with meta tags using the attribute 'property' (e.g. <meta property="title">), some URLs use the 'name' attribute instead (e.g. <meta name="title">)...

Therefore, I need to come up with a solution that can extract values from 'property', and if empty, retrieve values from 'name' instead...

I have attempted a few approaches so far without success... any suggestions?

Answer №1

Perhaps this

foreach ($tags AS $tag) {
    if ($tag->hasAttribute('property') &&
        strpos($tag->getAttribute('property'), 'og:') === 0) {
        $key = strtr(substr($tag->getAttribute('property'), 3), '-', '_');
        $page->_values[$key] = $tag->getAttribute('content');
    } else if ($tag->hasAttribute('name') &&
        strpos($tag->getAttribute('name'), 'og:') === 0) {
        $key = strtr(substr($tag->getAttribute('name'), 3), '-', '_');
        $page->_values[$key] = $tag->getAttribute('content');
    }
}

OZ_ pointed out that you could utilize str_ireplace to change all meta name to meta property.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieving information from an ajax array in PHP

I am currently attempting to retrieve an array of data using AJAX on the PHP side, but I am facing difficulties in accessing the values in PHP. Here is my JavaScript code snippet: console.log(obj); $.ajax({ method: 'POST', url: '/in ...

Is there a way to prevent this picture from shifting?

I am currently revamping the content on my work website using Joomla. I have received the old copy and now I need to enhance it. The website in question is 24x7cloud.co.uk. At the bottom of the page, I aim to include an "Accreditation's" section. Howe ...

Using PHP loops to verify the sequence of a given set of numbers

I am attempting to iterate through a collection of records, each with a "number" attribute. My goal is to determine if there are 3 consecutive records, for example 6, 7, and 8. I believe I am close with the code below, but I have encountered an issue in t ...

What methods can I employ to utilize the name attribute for POST requests instead of the ID attribute in TinyMCE?

My inline TinyMCE form sends content to qry.php with the key "edit_me". I prefer the default behavior of sending content using the name attribute instead. <script type="text/javascript"> tinymce.init({ selector: '#edit_me', ...

Symfony2 does not receive any feedback from the Ajax request

Perform an ajax POST request with no response: Here is the ajax request code snippet: $.ajax({ method: 'POST', url: "{{ path('app-like-add') }}", data: { imageId: id }, success: function(response) { ...

The process of transferring SHA1 passwords created through PHP to Bcrypt in JavaScript

My journey into the realm of encryption is a bit new, and after spending a few days on this, I find myself in need of assistance. The goal is to email the users, have them log in, verify their password against SHA1, and then encrypt the provided password ...

Tips for structuring a SQL query result in an AngularJS application

Forgive me if this code is not up to par with the best standards, as I am still relatively new to angular.js. The issue I am facing is that when the data is returned from my query, it appears as a block of text. Despite using echo statements in search.php ...

I'm encountering a "confirm" error within the data table. Any suggestions on how to resolve this issue?

When I try to use two datatables columns in confirm, an error occurs when the text 'do you want cancel?' is displayed. The issue seems to be with the text itself and not the code. How should we go about fixing this problem? This is my current cod ...

Greatly enhance the speed of inserting 10 million rows into a MySQL database

, there is a HTML content containing PHP code that iterates through numerous XML files and inserts data into a MySQL database. The script processes a large number of files but is currently experiencing slow insertion speeds. To enhance performance, optimiz ...

Error: Unexpected curly bracket found, expecting a comma or semicolon instead issue

Struggling to identify the bug in my code. Could really use some assistance. <?php if(isset($_SESSION["pkg_error"])); ?> <div class="error_msg_cont"> <?php foreach($_SESSION["pkg_error"] as $error) { echo $error. "&l ...

Issues encountered with jQuery Form Plugin failing to pass a string value to PHP

I'm currently experimenting with the jQuery form plugin (http://jquery.malsup.com/form) to handle photo uploads and previews. However, I'm encountering an issue where the data strings expected to be sent to PHP using the ajaxForm function are com ...

When an Ajax post request is made, the data being sent is appended to the JSON response

Having a dilemma with my ajax call: $.ajax({ url: '/assets/functions.php', type: 'POST', data: { "functionCall": "get-uploads", "type": type }, dataType: 'json', success: function (data ...

mysql query output showing multiple instances of the same data after performing a group_by operation

When using the group_by function in MySQL with a large dataset of 116,000 records, I noticed that there are duplicate entries. How can I address this issue? SELECT field1, field2, field3 FROM table GROUP BY field2 ORDER BY 'field2' ASC field1| ...

Updating webpage links based on $_get parameters

Currently, I am using $_GET['base'] to determine the homepage that a user visits on my website. This results in either localhost/?base=administrator or localhost/?base=guest I am also using this method to control which page the user is currentl ...

Is there a way to define a varying number of OR conditions in a Doctrine SQL Where clause?

Is there a way to dynamically generate a Doctrine ORM query that mimics the following SQL statement, considering that the number of values in the 'OR' clause may vary with each execution? SELECT * FROM table1 WHERE table1.group = 1 OR 2 OR ...

Two instances of a PHP Class created despite employing the Singleton design pattern

Object Oriented PHP Class: if( ! class_exists('MY_CLASS') ) : class MY_CLASS { private static $_instance = null; private static $counter = 0; private function __construct() { self::$counter++; // Perform actio ...

Utilize PHP to filter JSON data and dynamically populate a dropdown menu with the results

In my PHP application, I have a JSON data set containing information about various users. I need to filter out the individuals with a status of Active and display them in a dropdown list. How can I achieve this? Below is the JSON data: [ { "usernam ...

Struggling to construct a binary tree as my descendants are not arranged in the right sequence

I am currently working on building a binary tree using PHP, MySQL, and a jQuery plugin developed by Frank-Mich. Here is the progress I have made so far... DATABASE STRUCTURE CREATE TABLE IF NOT EXISTS `members` ( `id` int(11) NOT NULL AUTO_INCREMENT, ...

Assigning objects in PHP

As a PHP learner, I am seeking assistance with the following PHP Object-Oriented Programming (OOP) code: class x{} $x = new x; $x->name = "Chandan"; class y extends x {} // Inheritance $y = new y; var_dump($x); // object X; Shows Name property va ...

Is mysql(i)_real_escape_string a reliable method for ensuring data safety?

function CustomQuery() { $arguments = func_get_args (); if (sizeof ($arguments) > 0) { $query_string = $arguments[0]; for ($index = 1; $index < sizeof ($arguments); $index++) $query_string = preg_replac ...