如何使用PHP将span标记中的文本存储到变量中


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

我刚开始学习PHP。我有一个名为"address"的字符串,其中包含HTML,看起来像:

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

我想知道如何将"239 House"存储到一个名为"address1"的变量

这是这个问题的灵感来源:PHP解析HTML代码

您可以使用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;

在线视频测试。

链接:

  • http://en.wikipedia.org/wiki/XPath#External_links

  • http://php.net/manual/en/class.domdocument.php

  • http://php.net/manual/en/domxpath.query.php

你也可以试试new simplexmlelement(XMLString):

  • http://php.net/manual/en/simplexmlelement.xpath.php