insert echo into the specific html element like div which has an id or class

insert echo into the specific html element like div which has an id or class

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Targeted Content Injection in Legacy PHP Applications

The code snippet you provided relies on the deprecated mysql_* extension, which was removed from the core PHP distribution many years ago. While your current implementation works for generating inline HTML strings within a loop, it lacks the flexibility to dynamically target specific DOM elements. To inject content into a specific <div> identified by an ID or class, you must shift from string concatenation to manipulating the Document Object Model (DOM).

The most effective approach involves rendering a partial template where the dynamic data is injected at a predefined placeholder. Instead of echoing raw HTML tags directly inside your loop, pass the row data into a function that accepts the target element's ID or class as an argument. This function will locate the element and append the inner content.

Here is how you can refactor your logic using DOMDocument and DOMElement:

<?php
// Initialize the DOM document with UTF-8 encoding to handle special characters correctly
$dom = new DOMDocument();
$dom->loadHTML('<!DOCTYPE html><html><body></body></html>', LIBXML_NOENT); // Suppress warnings for incomplete HTML in snippets

// Locate the container element by ID or Class
// Example: Targeting an element with id="content-area"
$container = $dom->getElementById('content-area'); 

if (!$container) {
    // Alternatively, search by class name if no ID exists
    $container = $dom->getElementsByClassName('item-container')[0]; 
}

// Iterate through your database results
while($row = mysql_fetch_array($result)) {
    
    // Create the image element separately before appending to the container
    $imgNode = $dom->createElement('img');
    $imgNode->setAttribute('src', $row['name']);
    
    // Create the div wrapper for text content
    $divName = $dom->createElement('div');
    $divName->nodeValue = $row['name'];
    
    $divTitle = $dom->createElement('div');
    $divTitle->nodeValue = $row['title'];

    $divDesc = $dom->createElement('div');
    $divDesc->nodeValue = $row['description'];

    $divLink = $dom->createElement('div');
    $divLink->setAttribute('href', $row['link']); // Assuming 'link' is a URL
    $divLink->appendChild($dom->createTextNode($row['link']));

    // Create a new parent wrapper for this iteration's content, or append directly if structure allows
    $wrapper = $dom->createElement('div');
    
    $wrapper->appendChild($imgNode);
    $wrapper->appendChild($divName);
    $wrapper->appendChild($divTitle);
    $wrapper->appendChild($divDesc);
    $wrapper->appendChild($divLink);

    // Append the new content to the target container
    $container->appendChild($wrapper);
}

// Output the final HTML
echo $dom->saveHTML();
?>

Why Use DOM Manipulation?

Directly echoing strings like echo "<div>...</div>" inside a loop often leads to "spaghetti code" where you lose control over document structure. When you want to insert into a specific element, the DOM API provides methods like appendChild, insertBefore, and removeChild. These methods handle the tree structure explicitly, ensuring that your new nodes are children of the intended parent.

Using getElementById or getElementsByClassName allows you to decouple your output logic from your HTML markup. You can define your target container once in your template (e.g., <div id="main-content"></div>) and populate it regardless of how many rows come back from the database. This makes maintenance significantly easier; if you need to change the CSS for that specific div later, you only update the stylesheet, not the PHP logic.

Security Considerations

Your original code concatenates raw database values directly into HTML strings: echo '&lt;img src="'.$row['name'].'" /&gt;'. This is a critical vulnerability known as Cross-Site Scripting (XSS). If a user controls the value in the name column and inputs <script>alert(1)</script>, that script will execute in every visitor's browser.

When using DOM nodes, you must explicitly escape data before assigning it to node values or attributes. The DOMDocument does not automatically escape content. You should use htmlspecialchars() with the ENT_QUOTES flag before assigning text:

$divName->nodeValue = htmlspecialchars($row['name'], ENT_QUOTES, 'UTF-8');

Additionally, since you are using the legacy mysql_connect, consider migrating to PDO or MySQLi. These modern extensions support prepared statements, which handle both security (preventing SQL injection) and data type safety much more robustly. If you are starting a new project or can refactor easily, integrating your logic into a Laravel application would leverage built-in escaping helpers and ORM features that reduce the risk of these common pitfalls.

Final Thoughts on Implementation

By separating the creation of elements from their insertion point, you gain precise control over where content appears in the DOM. This pattern scales well as your application grows. Whether you are targeting a div with an ID or iterating through a list of items, treating HTML structure as an object graph rather than a string builder is the industry standard for maintainable web applications.

Our network