Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract string between html tags in php

I want to extract string between html tags and convert it into other language using google api and to append the string with html tags.

For example,

<b>This is an example</b>

I want to extract the string "This is an example" and convert it into other language and then again append the string with bold tag.

Could anyone know how to proceed with this?

Regards Rekha

like image 747
Rekha Avatar asked Sep 02 '25 10:09

Rekha


2 Answers

The simplest way is to just use DOM parsing to get the contents of the HTML tags. However, you need to specify which tags you want to get the contents for. For example, you wouldn't want the contents of table or tr, but you may want the contents of td. Below is an example of how you would get the contents of all the b tags and replace the text between them.

$dom_doc = new DOMDocument();
$html_file = file_get_contents('file.html');
// The next line will likely generate lots of warnings if your html isn't perfect
// Put an @ in front to suppress the warnings once you review them
$dom_doc->loadHTML( $html_file );
// Get all references to <b> tag
$tags_b = $dom_doc->getElementsByTagName('b');
// Extract text value and replace with something else
foreach($tags_b as $tag) {
    $tag_value = $tag->nodeValue;
    // get translation of tag_value
    $translated_val = get_translation_from_google();
    $tag->nodeValue = $translated_val;
}
// save page with translated text
$translated_page = $dom_doc->saveHTML();

Edit: corrected spelling of file_get_contents and added ; after $translated_val

like image 186
Brent Baisley Avatar answered Sep 05 '25 00:09

Brent Baisley


$text = '<b>This is an example</b>';
$strippedText = strip_tags($text);
echo $strippedText; // This is an example
like image 31
hsz Avatar answered Sep 05 '25 00:09

hsz