0

I am currently working on a project that requires me to query an XML file like php to return a value that matches the request. Take a look at the XML:

<ENVELOPE>
 <MASTER>
  <STKDETNAME>004-011</STKDETNAME>
  <STKPNO>PTN771</STKPNO>
  <STKPRICE></STKPRICE>
  <STKOPBAL>500</STKOPBAL>
 </MASTER>
 <MASTER>
  <STKDETNAME>004-012</STKDETNAME>
  <STKPNO>PTN772</STKPNO>
  <STKPRICE></STKPRICE>
  <STKOPBAL>500</STKOPBAL>
 </MASTER>
 <MASTER>
  <STKDETNAME>004-013</STKDETNAME>
  <STKPNO>PTN773</STKPNO>
  <STKPRICE></STKPRICE>
  <STKOPBAL>1000</STKOPBAL>
 </MASTER>
 <MASTER>
  <STKDETNAME>004-014</STKDETNAME>
  <STKPNO>PTN774</STKPNO>
  <STKPRICE></STKPRICE>
  <STKOPBAL>1000</STKOPBAL>
 </MASTER>
 <MASTER>
  <STKDETNAME>004-015</STKDETNAME>
  <STKPNO>PTN775</STKPNO>
  <STKPRICE>400</STKPRICE>
  <STKOPBAL>1000</STKOPBAL>
 </MASTER>
</ENVELOPE>

Now, I want to get the STKPRICE AND STKOPBAL for a SKTPNO= PTN773. This is what i have seen so far, but i don't know how to get the two values. I am new to XML.

 $file = 'stocksum.xml';//same file as above
     $xmlfile = simplexml_load_file($file);
     $partno = PTN775;
     $fnd = $xmlfile->xpath('/ENVELOPE/MASTER/STKPNO[.="$partno"]');

1 Answer 1

1

There are a couple of issues with the code which are just syntax problems, these are the partno needing quotes and when building the XPath expression, you use single quotes so it doesn't insert the actual part number.

BUT to get to your actual problem, if you change your XPath to the one used here, this will find the <MASTER> element whose <STKPNO> is the one your after. So then you can refer to the elements withing the <MASTER> element using standard SimpleXML object notation...

$partno = 'PTN775';
$fnd = $xmlfile->xpath('/ENVELOPE/MASTER[STKPNO="'.$partno.'"]');

echo $fnd[0]->STKPRICE.PHP_EOL;

Note that as xpath() returns a list of matches, I use $fnd[0] to get the first one.

Code which also has a check to see if the part actually exists...

$xmlfile = simplexml_load_file($file);

$partno = 'PTN7751';
$fnd = $xmlfile->xpath('/ENVELOPE/MASTER[STKPNO="'.$partno.'"]');

if ( count($fnd) == 0 ) {
    echo "Not found";
}
else    {
    echo $fnd[0]->STKPRICE.PHP_EOL;
}
Sign up to request clarification or add additional context in comments.

2 Comments

It displays all the content with : echo $xmlfile->asXML(); So, what should i do to get the exact value

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.