d0ve
d0ve

Reputation: 63

Getting specific item from XML

I searched the web and the stackoverflow archive and haven't found anything that really helped me solve this problem.

I have the following XML file

<?xml version="1.0"?>
<Results>
  <Result>
    <Step>001</Step>
    <State>1</State>
    <Complete>true</Complete>
  </Result>
    <Result>
        <Step>002</Step>
        <State>1</State>
        <Complete>true</Complete>
    </Result>
    <Result>
        <Step>003</Step>
        <State>1</State>
        <Complete>false</Complete>
    </Result>
</Results>

And I want to get the value of Complete with the help of Step. So basically, the Client calls getSuccess(param) where param is an entered Step e.g. 002 . I then want to get the value of this specific Array (or Result tree). My Code looks like this right now

public function getSuccess($step){

    $doc = new DOMDocument('1.0');
    $doc->formatOutput = true;
    $doc->Load("./API/response.xml");

    // Borat: >>Great Success!<<
    $Borat = $doc->getElementsByTagName('Result');
    foreach ($Borat as $Result) {
        ###########
        #CODE HERE#
        ###########
    }
}

I am now looking for the exact code to echo the result.

Thanks in advance. And if there exists a topic that solved my problem, please let me know and I will close this one.

Upvotes: 0

Views: 59

Answers (2)

Raymond
Raymond

Reputation: 78

Don't know if its the way to go but you can try this:

public function getSuccess($step)
{
    $xml_string = file_get_contents("./API/response.xml");
    $xml_data = new SimpleXMLElement($xml_string);

    // Search for the parent bij $step
    $nodes = $xml_data->xpath('//Results/Result/Step[.="'.$step.'"]/parent::*');
    return $nodes[0];
}

$Result = getSuccess('002');
print_r($Result);

Should output: SimpleXMLElement Object ( [Step] => 002 [State] => 1 [Complete] => true )

Upvotes: 3

chirag
chirag

Reputation: 484

You can compare step in IF condition and get any node of XML you want.

For Example: I am getting 'State' node here.

function getSuccess($step) {

    if (file_exists("./response.xml")) {
        $xml = simplexml_load_file("./response.xml");

        foreach ($xml as $Result) {

            if ($step == $Result->Step) {
                $State = $Result->State;
                return $State;
            }
        }
    } else {
        exit('Failed to open test.xml.');
    }

}

echo getSuccess('001');

Hope this helps.

Upvotes: 3

Related Questions