1

I need to avoid eval() again. I want to access a multidimensional array like this:

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

The thing is that $explode_path[0] and $explode_path[1] are calculated through a for loop:

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

Right now the entire code looks like this:

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 />';
}

I can't figure out how I can access the $xml2array array that way:

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

Any help would be highly appreciated!

3
  • "I need to avoid eval() again" -- thats a good start :-) Commented May 5, 2012 at 3:58
  • What is the output of readfile_chunked? Commented May 5, 2012 at 4:01
  • readfile_chunked() is a custom function like file_get_contents(). It downloads a large file into smaller chunks of bytes in order to avoid large memory consumption. When the file has finished downloading it returns the file contents. Commented May 5, 2012 at 4:05

1 Answer 1

1

What about replacing your getValues() function with:

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;
}

Edit: Cleaner version:

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

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

    return $items;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Great, but wait a second, I'll get you an even cleaner version
OK, now that's way too awesome Thank you so much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.