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
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
$text = '<b>This is an example</b>';
$strippedText = strip_tags($text);
echo $strippedText; // This is an example
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With