Skip to content
PHP Logo

What are some best practices for ensuring that only specific content (such as text) is extracted and displayed from an external website in PHP?

When extracting specific content from an external website in PHP, it's important to use an HTML parser to target and extract only the desired text. One common approach is to use a library like Simple HTML DOM Parser to parse the HTML content and then filter out unwanted elements based on their attributes or structure.

php
// Include the Simple HTML DOM Parser library
include('simple_html_dom.php');

// URL of the external website
$url = 'https://www.example.com';

// Create a new DOM object
$html = file_get_html($url);

// Find and extract specific content based on HTML tags or attributes
$specific_content = $html->find('div#content', 0)->plaintext;

// Display the extracted content
echo $specific_content;