php associative arrays, regex, array

2019-06-14 08:17发布

I currently have the following code :

$content = "
<name>Manufacturer</name><value>John Deere</value><name>Year</name><value>2001</value><name>Location</name><value>NSW</value><name>Hours</name><value>6320</value>";

I need to find a method to create and array as name=>value. E.g Manufacturer => John Deere.

Can anyone help me with a simple code snipped I tried some regex but doesn't even work to extract the names or values, e.g.:

$pattern = "/<name>Manufacturer<\/name><value>(.*)<\/value>/";
preg_match_all($pattern, $content, $matches);
$st_selval = $matches[1][0];

7条回答
Evening l夕情丶
2楼-- · 2019-06-14 09:05

I'll edit as my PHP is wrong, but here's some PHP (pseudo-)code to give some direction.

$pattern = '|<name>([^<]*)</name>\s*<value>([^<]*)</value>|'
preg_match_all($pattern, $content, $matches, PREG_SET_ORDER);
for($i = 0; $i < count($matches); $i++) {
    $arr[$matches[$i][1]] = $matches[$i][2];
}

$arr is the array you want to store the name/value pairs.

查看更多
登录 后发表回答