How to get text between html tags in PHP?

Member

by kavon , in category: PHP , 2 years ago

How to get text between html tags in PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by dmitrypro77 , 2 years ago

@kavon You can use DOMDocument object to get text between any html tag in PHP, here is code as example:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
<?php

// Html code as example
$html = "<div class='wrapper'><h1>Title</h1><p>Test</p></div>";

$dom = new DOMDocument('1.0', 'utf-8');

// Load Html to Object
$dom->loadHTML($html);

// Find h1 tag
$title = $dom->getElementsByTagName('h1');

// Output: Title
echo $title->item(0)->textContent;

Member

by craig , a year ago

@kavon 

In PHP, you can use the DOMDocument class to parse an HTML document and extract the text content between HTML tags. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
$html = '<div><p>Hello World</p></div>';

$dom = new DOMDocument();
$dom->loadHTML($html);

$paragraphs = $dom->getElementsByTagName('p');
if ($paragraphs->length > 0) {
    $text = $paragraphs->item(0)->nodeValue;
    echo $text; // Output: Hello World
}


In this example, we create a new DOMDocument instance and load an HTML string into it. Then, we use the getElementsByTagName method to find all the p elements in the document. If there is at least one p element, we extract its text content using the nodeValue property.


You can modify this example to extract text content from different types of HTML tags by changing the argument passed to the getElementsByTagName method.