如何在UL中将UL中的值转换为关联数组

时间:2022-06-13 08:50:31

I have a ul list like this:

我有一个像这样的ul列表:

<ul>
    <li>                        
       <div class="time">18:45</div>
       <div class="info">description goes here</div>
       <div class="clearAll"></div>
    </li>

    <li>                        
       <div class="time">19:15</div>
       <div class="info">some info</div>
   <div class="clearAll"></div>
    </li>
</ul>

How can I turn this into an array like this:

我怎么能把它变成这样的数组:

$array = array(
    1 => array('18:45','description goes here');
    1 => array('19:15','some info');
);

2 个解决方案

#1


3  

Stay away from a regex for this. DOMDocument is your friend:

远离正则表达式。 DOMDocument是你的朋友:

$dom = new DOMDocument;
$dom->loadHTML( $theHTMLstring );
$array = array();

foreach ( $dom->getElementsByTagName('li') as $li ) {

    $divs = $li->getElementsByTagName('div');

    $array[] = array(
        $divs->item(0)->textContent,
        $divs->item(1)->textContent
    );
}

See it here in action: http://codepad.viper-7.com/5ExOqJ

请在此处查看:http://codepad.viper-7.com/5ExOqJ

#2


0  

By not using regex:

不使用正则表达式:

$sx = new SimpleXMLElement($xml);

foreach ($sx->xpath('//li') as $node) {
   $time = current($node->xpath("div[@class='time']"));
   $time = "$time";

   $info = current($node->xpath("div[@class='info']"));
   $info = "$info";

   $data[] = array($time, $info);
}

http://codepad.viper-7.com/lo8k5c

http://codepad.viper-7.com/lo8k5c

#1


3  

Stay away from a regex for this. DOMDocument is your friend:

远离正则表达式。 DOMDocument是你的朋友:

$dom = new DOMDocument;
$dom->loadHTML( $theHTMLstring );
$array = array();

foreach ( $dom->getElementsByTagName('li') as $li ) {

    $divs = $li->getElementsByTagName('div');

    $array[] = array(
        $divs->item(0)->textContent,
        $divs->item(1)->textContent
    );
}

See it here in action: http://codepad.viper-7.com/5ExOqJ

请在此处查看:http://codepad.viper-7.com/5ExOqJ

#2


0  

By not using regex:

不使用正则表达式:

$sx = new SimpleXMLElement($xml);

foreach ($sx->xpath('//li') as $node) {
   $time = current($node->xpath("div[@class='time']"));
   $time = "$time";

   $info = current($node->xpath("div[@class='info']"));
   $info = "$info";

   $data[] = array($time, $info);
}

http://codepad.viper-7.com/lo8k5c

http://codepad.viper-7.com/lo8k5c