1

我需要使用 php 从 span 标签中获取多个值,例如:

   <div>
    <span class='name'>name value</span>
    <span class='city'>city name</span>
    <span class='street'>street name</span>
    <span class='phone'>+17240000000</span>
    </div>
  <div>
   <span class='name'>name value 2</span>
   <span class='city'>city name 2</span>
   <span class='street'>street name 2</span>
   <span class='phone'>+17240000000 2</span>
  </div> 

我必须使用跨度类获取跨度值,我尝试使用此代码来获取该值,并且它仅适用于 1 个值,例如“名称”:

<?
$html = "<div>
         <span class='name'>name value</span>
         <span class='city'>city name</span>
         <span class='street'>street name</span>
         <span class='phone'>+17240000000</span>
         </div>
         <div>
         <span class='name'>name value 2</span>
         <span class='city'>city name 2</span>
         <span class='street'>street name 2</span>
         <span class='phone'>+17240000000 2</span>
         </div>";
$dom = new DOMDocument();
@$dom->loadHTML($html);
$dom_xpath = new DOMXPath($dom);

$entries = $dom_xpath->evaluate("//span[@class='name']");
foreach ($entries as $entry) {
   echo  $entry->nodeValue."<br />";
}
?>

有没有人可以帮助我修改代码,以便我可以获得所有值

谢谢

4

1 回答 1

2

尝试改变

......
$dom = new DOMDocument();
@$dom->loadHTML($html);

foreach($dom->getElementsByTagName('span') as $span){
  echo $span->nodeValue . '<br>';
  //echo $span->getAttribute('class');
}

基于上述格式,您可能想尝试一下(假设 className 永远不会改变并且始终存在)

......
$dom = new DOMDocument();
@$dom->loadHTML($html);

$result = array();
foreach ($dom->getElementsByTagName('div') as $div){
    $temp = array();
    foreach($div->getElementsByTagName('span') as $span){
        $temp[$span->getAttribute('class')] = $span->nodeValue; 
    }

    // db insert here
    // You may want to do some error check before inserting the data by making sure the array key exist 
    // need to escape data (SQL_injection)
    //mysql_query("INSERT INTO db (`name`,`city`,`street`,`phone`) VALUES('{$temp['name']}','{$temp['city']}','{$temp['street']}','{$temp['phone']}')");

    $result[] = $temp;

}

print_r($result);

您需要在将值插入 db(sql 注入)之前对其进行转义,并且需要更有效地进行批量插入 - 阅读更多内容,通过 php 数组将多行插入 mysqlhttp://en.wikipedia.org/wiki /SQL_injection

或者

 $entries = $dom_xpath->evaluate("//span[@class='name']")

 $entries = $dom_xpath->evaluate("//span")
于 2012-10-27T00:06:58.147 回答