How to add ‘data-caption’ inside an anchor tag

You can try this code to add the new attribute in the html code:

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

foreach ($dom->getElementsByTagName("a') as $item) {

    $item->setAttribute('data-caption', 'This is an anchor tag');
    echo $dom->saveHTML();
    exit;
}