CoderJoe
CoderJoe

Reputation: 447

Get a specific field from a xml file

I am trying to loop through an xml file and check all the email fields to see if they match a predefined email and if it does grab the contactid

The issue I am having is the structure of the xml file doesnt seem to be put together in a way that makes looping through it easy.

For example I am using this snippet to parse the xml file

$p = xml_parser_create();
            xml_parse_into_struct($p,$response,$vals,$index);
            xml_parser_free($p);

            echo "\nVals array\n";

            print_r($vals);
?>

Using this I can get the contactid of the first row by doing $vals[4] but the structure of the file does not let me loop to check other fields that I can think of.

I have tried other methods of parsing the xml file but they all seem to look the same as the one in the link below

This is the xml file that $response returns http://deathcrow.altervista.org/response.xml

How can I loop over all the emails in the xml file and cross reference them and then grab the contactid of the one that matches?

Upvotes: 1

Views: 2136

Answers (1)

Nigel Ren
Nigel Ren

Reputation: 57121

Using SimpleXML and XPath can make this 'easier'. The XPath is the main part which will allow you to find the data your after...

$xml = simplexml_load_file("http://deathcrow.altervista.org/response.xml");

// Test email to find
$email = '[email protected]';   
$contactID = $xml->xpath("//row[FL[@val='Email'][text()='$email']]/FL[@val='CONTACTID']");

echo (string)$contactID[0];

outputs

2594788000014076002

To break down the XPath...

//row[FL[@val='Email'][text()='$email']]/FL[@val='CONTACTID']

This looks for a row element with the attribute val (@val) for the Email and then checks the value (text()) is the email address your after.

The final

/FL[@val='CONTACTID']

picks out the FL element for the contactID.

As XPath will return a list of matches, the last line uses $contactID[0] to just return the first match. Using (string) ensures that it will be a string rather than a SimpleXMLElement.

Upvotes: 1

Related Questions