How to Get HTML Tag Value in PHP | DOMDocument Object

Reading Time: 4 minutes
10,932 Views

Inside this article we will see the concept i.e How to get HTML tag value in PHP. If you are looking of an article which makes you understand about How to parse HTML tags and elements then this article is best to get those concept.

DOMDocument object of PHP used to parse HTML string value. If we want to get tag name, it’s values etc then object will help for all those.

DOMDocument of PHP also termed as PHP DOM Parser. We will see step by step concept to get the HTML tag value using DOM parser.

Learn More –

Let’s get started.


Example 1: PHP Get HTML Element Value

Create a file index.php at your localhost directory. Open index.php and write this complete code into it.

<?php

// HTML String
$htmlElement = "<html><body><p>This is Sample Text Message 1</p><p>This is Sample Text Message 2</p><p>This is Sample Text Message 3</p></body></html>";

// DOM Parser Object
$htmlDom = new DOMDocument();
$htmlDom->loadHTML($htmlElement);

$paragraphTags = $htmlDom->getElementsByTagName('p');

foreach ($paragraphTags as $paragraph) {
    echo $paragraph->nodeValue . "<br/>";
}

Concept

Here, we are getting all paragraph tags by Tag “P”

$paragraphTags = $htmlDom->getElementsByTagName('p');

Output

When we run index.php. Here is the output

This is Sample Text Message 1
This is Sample Text Message 2
This is Sample Text Message 3

Example 2: PHP Get HTML Element Value By ID

Let’s assume the given string value for this example. Open index.php and write this complete code into it.

<?php

// HTML String
$htmlString = "<html><body><p id='sampleParagraph'>This is a sample text message for Testing...</p></body></html>";

// DOM Parser Object
$htmlDom = new DOMDocument();
$htmlDom->loadHTML($htmlString);
   
$paragraphTagValue = $htmlDom->getElementById('sampleParagraph')->nodeValue;
  
echo $paragraphTagValue;

Concept

Here, nodeValue returns value of node by it’s ID.

$htmlDom->getElementById('sampleParagraph')->nodeValue;

Output

When we run index.php. Here is the output

This is a sample text message for Testing…

We hope this article helped you to learn How to Get HTML Tag Value in PHP i.e DOMDocument Object in a very detailed way.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.