如何获取数组中的标签内容?

时间:2015-03-26 17:47:55

标签: php woocommerce

我正在使用woocommerce,而且函数返回以下格式的项目数据

<dl class="variation">
<dt>options:</dt><dd>redwood-120mm-x-28mm</dd>
<dt>length:</dt><dd>3.6</dd>
<dt>linear metres:</dt><dd>500</dd>
</dl>

我想将这些数据输入到数组中,如下所示;

array("options:" => "redwood-120mm-x-28mm", "length:"=> "3.6", "linear metres:" => "500");

我该怎么做?

这是功能:

global $woocommerce;
     foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $cart_item ) {
        echo $woocommerce->cart->get_item_data( $cart_item );

     }
}

1 个答案:

答案 0 :(得分:1)

你可以通过正则表达式来完成它,也许你想在PHP中为DOM做一个镜头。

我的解释是在评论中的代码中。

//String to parse
$string = '<dl class="variation">
<dt>options:</dt><dd>redwood-120mm-x-28mm</dd>
<dt>length:</dt><dd>3.6</dd>
<dt>linear metres:</dt><dd>500</dd>
</dl>';

//Keys, you want to find
$keys = array('options', 'length', 'linear metres');

//The result array
$result = array();

//Loop through the keys
foreach ($keys as $key) {
    //Insert the result into the result array
    $result[$key] = getValueByKey($key, $string);
}

//Show results
var_dump($result);

function getValueByKey($key, $string) {
    //The pattern by key
    $pattern = '/<dt>' . $key . ':<\/dt><dd>(.*?)<\/dd>/i';

    //Initialize a match array
    $matches = array();

    //Do the regular expression
    preg_match($pattern, $string, $matches);
    if (!empty($matches[1])) {
        //If there are match, then return with it
        return $matches[1];
    }
    //Otherwise return with false
    return false;
}

输出为:

array (size=3)
  'options' => string 'redwood-120mm-x-28mm' (length=20)
  'length' => string '3.6' (length=3)
  'linear metres' => string '500' (length=3)