简体   繁体   中英

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:

<div class="address_row">
  <span class="address1">239 House</span>
  <span class="address2">Street South</span>
</div>

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

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 = '<div class="address_row">
  <span class="address1">239 House</span>
  <span class="address2">Street South</span>
</div>';

$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

Could try so, XPath can help in your project:

<?php
$str = '<div class="address_row">
  <span class="address1">239 House</span>
  <span class="address2">Street South</span>
</div>';

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

$b = new DomXPath($a);//set DOM from XPath

//Get <span class=address1>
$address1 = trim($b->query('//*[@class="address1"]')->item(0)->nodeValue);

//Get <span class=address2>
$address2 = trim($b->query('//*[@class="address2"]')->item(0)->nodeValue);

//show variables
echo 'address2: ', $address1, '<br>';
echo 'address2: ', $address2;

Test online in ideone .

Links:

you can also try new simplexmlelement(XMLString) :

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM