1

我需要再次避免 eval() 。我想访问这样的多维数组:

$items = $xml2array[$explode_path[0]][$explode_path[1]];

问题是 $explode_path[0] 和 $explode_path[1] 是通过 for 循环计算的:

for($i=0; $i<$count_explode; $i++) { }

现在整个代码如下所示:

function getValues($contents, $xml_path) {
    $explode_path = explode('->', $xml_path);
    $count_explode = count($explode_path);
    $xml2array = xml2array($contents);

    $correct_string = '$items = $xml2array';

    for($i=0; $i<$count_explode; $i++) {
        $correct_string .= '[$explode_path['.$i.']]';
    }

    $correct_string .= ';';
    eval($correct_string);
    return $items;
}

$contents = readfile_chunked($feed_url, true);
$items = getValues($contents, 'deals->deal'); # will get deals->deal from MySQL

foreach($items as $item) {
    echo $item['deal_title']['value'].' - '.$item['dealsite']['value'].'<br />';
}

我不知道如何以这种方式访问​​ $xml2array 数组:

$items = $xml2array[$explode_path[0]][$explode_path[1]];

任何帮助将不胜感激!

4

1 回答 1

1

getValues()用以下内容替换您的功能怎么样:

function getValues($contents, $xml_path) {
    $explode_path = explode('->', $xml_path);
    $count_explode = count($explode_path);
    $items = xml2array($contents);

    for($i=0; $i<$count_explode; $i++) {
        $items = $items[$explode_path[$i]];
    }

    return $items;
}

编辑:更清洁的版本:

function getValues($contents, $xml_path) {
    $items = xml2array($contents);

    foreach(explode('->', $xml_path) as $k)
    {
        $items = $items[$k];
    }

    return $items;
}
于 2012-05-05T04:05:25.750 回答