0

Hi i have this type of XML type exactly. And i need to get information using PHP xpath. XML looks like:

<row>
<id>1</id>
<product>
    <prodRow>
        <PID>Aa</PID>
    </prodRow>
    <prodRow>
        <PID>Ab</PID>
    </prodRow>
</product>
</row>
<row>
<id>2</id>
<product>
    <prodRow>
        <PID>Ba</PID>
    </prodRow>
    <prodRow>
        <PID>Bb</PID>
    </prodRow>
</product>
</row>
<row>
<id>3</id>
<product>
    <prodRow>
        <PID>Ca</PID>
    </prodRow>
    <prodRow>
        <PID>Cb</PID>
    </prodRow>
</product>
</row>

PHP script:

    if(file_exists("band.xml"))
    {
   $DOM = new DOMDocument();
       $DOM->load("band.xml");
   $xpath = new DOMXPath($DOM);
   $row = $xpath->query("//row/id");
   $prodRowID = $xpath->query("//row/product/prodRow");

    foreach($row as $vID)
    {
    echo "<b>".$vID->nodeValue."</b><br /><br />";  

    foreach($prodRowID as $pID)
    {
                            $prodID = $pID->getElementsByTagName("PID");
            echo "<b>".$prodID->item(0)->nodeValue."</b><br /><br />";  
    }       

    }

      }

The answer i get and don't know how to do that, everytime the row is reached, the PID is printing from all rows:

1
Aa, Ab, Ba, Bb, Ca, Cb
2
Aa, Ab, Ba, Bb, Ca, Cb
3
Aa, Ab, Ba, Bb, Ca, Cb

The answer i need to get:

1
Aa, Ab
2
Ba, Bb
3
Ca, Cb

Thanks for answer this is my headache, don't know how to do that.

2 Answers 2

1

You need to select the prodRows inside the first foreach, indicate the context node, and not use an absolute XPath:

foreach($row as $vID)
{
   echo "<b>".$vID->nodeValue."</b><br /><br />";  

   $prodRowID = $xpath->query("../product/prodRow", $vID);
   foreach($prodRowID as $pID)
   {
        echo "LIGA <b>".$pID->nodeValue."</b><br /><br />"; 
   }       
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks that helped very much, both answers were right :) You are the best. you helped me so far a lot JLRishe.
0

Your inner foreach does always the same because it does not refer in any way to your outer foreach. What you want to do is iterating over all //row nodes, then query id and product/prodRow from there with the context parameter of DOMXpath::query().

1 Comment

Thanks i will keep that in mind, you were right about this, i always refer in //row nodes, and JLRishe showed below how don't do that. Thanks both of you. Cheers !

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.