PHP - I would like to return values of attributes from xml file and retrieve their value from a predefined array

54 Views Asked by At

If I println($values) I will get the results of the correct attributes for each file fully written as shown in array as key on left but I would like to run the results against the array (valuesCodes) to get the values on right.

Any help would be greatly appreciated, I'm brand new to PHP.

$valuesCodes = array(
"Anfield" => "ANF",
"Lower" => "LOW",
"Burntown"=>"BUR");


foreach ($Files as $file) {
    $contents = simplexml_load_file($file);
    $values = $contents->Match->attributes()->stadium;
}
1

There are 1 best solutions below

0
Markus Zeller On

For best practice I renamed some variables (Look for PSR).

First of all the $valueCodes should be on top, else they are not known inside the foreach.

As it looked like your stadium value contain whitespaces or line breaks which can be eliminated by trimming them.

$valueCodes = [
    "Anfield"  => "ANF",
    "Lower"    => "LOW",
    "Burntown" => "BUR",
];

foreach ($files as $file) {
    $contents = simplexml_load_file($file);
    $value    = trim($contents->Match->attributes()->stadium);
    echo $valueCodes[$value] ?? 'N/A';
}