Pergunta

I have a ul list like this:

<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');
);
Foi útil?

Solução

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

$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

Outras dicas

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

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top