user3121403
user3121403

Reputation: 133

how do i get src and value of picture from html, and store it into a php variable?

i know DOMdocument can be used

$html = '<img id="garden" value="yellow" src="/images/flowers.png"
         alt="Image" width="100" height="100" />';

$doc = new DOMDocument();
$doc->loadHTML($html);
$xpath = new DOMXPath($doc);
$src = $xpath->evaluate("string(//img/@src)"); # "/images/image.jpg"

But how do i get the src and value from the img tag without hardcoding the whole tag into the $html variable?

<img id="garden" value="yellow" src="/images/flowers.png"
         alt="Image" width="100" height="100" />

Upvotes: 2

Views: 409

Answers (1)

This will do

<?php
$html='<img id="garden" value="yellow" src="/images/flowers.png"
         alt="Image" width="100" height="100" />';
$dom = new DOMDocument;
$dom->loadHTML($html);
foreach ($dom->getElementsByTagName('img') as $tag) {

echo $tag->getAttribute('value'); // "prints" yellow
    echo "<br>";
echo $tag->getAttribute('src'); // "prints" /images/flowers.png
}

Upvotes: 2

Related Questions