我刚开始学习PHP。我有一个名为“地址”的字符串,其中包含 HTML,如下所示:
<div class="address_row">
<span class="address1">239 House</span>
<span class="address2">Street South</span>
</div>
我想知道如何将“239 House”存储到一个名为“address1”的变量中
这是来自这个问题的灵感:PHP Parse HTML code
您可以使用http://php.net/manual/en/class.domelement.php执行此操作
这是示例代码;
$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
可以试试,XPath 可以帮助你的项目:
<?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;
在ideone中在线测试。
链接:
你也可以试试new simplexmlelement(XMLString)
: