我刚开始学习PHP。我有一个名为“address”的字符串,其中包含HTML:
<div class="address_row">
<span class="address1">239 House</span>
<span class="address2">Street South</span>
</div>
我想知道如何将“239 House”存储到一个名为“address1”
的变量中答案 0 :(得分:2)
这是这个问题的灵感来源: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
答案 1 :(得分:1)
可以尝试,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)
: