Sunday 5 January 2020

html - How to store text in a span tag into a variable using PHP?



I just started learning PHP. I have a string called "address" which contain HTML looks like:




239 House
Street South



I am wondering how to store "239 House" into a variable called "address1"


Answer



This is an inspiration from this question: PHP Parse HTML code



You can do this using http://php.net/manual/en/class.domelement.php



And here's the sample code;



$str = '

239 House
Street South
';

$DOM = new DOMDocument;
$DOM->loadHTML($str);

// all span elements
$items = $DOM->getElementsByTagName('span');
$span_list = array();

for($i = 0; $i < $items->length; $i++) {
$item = $items->item($i);
$span_list[$item->getAttribute('class')] = $item->nodeValue;
}
extract($span_list);

echo $address1; // 239 House
echo $address2; // Street South

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...