drll42469 2013-07-18 19:45
浏览 108
已采纳

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

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"

  • 写回答

2条回答 默认 最新

  • dsqe46004 2013-07-18 20:20
    关注

    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?