A
A
Alexander Nisel2015-04-24 17:56:04
PHP
Alexander Nisel, 2015-04-24 17:56:04

How to properly process XPath result in a loop?

Colleagues, good afternoon.
The task is to parse the xml file in such a way that by setting the values ​​of two elements, we get the value of the third element, which is at the same level as the two known ones.
There is an xml with something like this:

<Model>
            <idModel>26016</idModel>
            <sModel>DeLorean</sModel>
            <idMark>26015</idMark>
        </Model>
        <Model>
            <idModel>2986</idModel>
            <sModel>Avenger</sModel>
            <idMark>44</idMark>
        </Model>
        <Model>
            <idModel>2976</idModel>
            <sModel>Caliber</sModel>
            <idMark>44</idMark>
        </Model>
        <Model>
            <idModel>2977</idModel>
            <sModel>Caravan</sModel>
            <idMark>44</idMark>
        </Model>
        <Model>
            <idModel>3393</idModel>
            <sModel>Challenger</sModel>
            <idMark>44</idMark>
        </Model>
        <Model>
            <idModel>2978</idModel>
            <sModel>Charger</sModel>
            <idMark>44</idMark>
        </Model>

The processing itself is done like this:
foreach ($idref->xpath('//Model') as $item) {
          if ($item->idMark == $idmark && $item->sModel == $smodel) {
            $idmodel = $item->idModel;
            break;
          }
        }

That is, knowing $idmark and $smodel, we need to get the value of $idmodel.
Most likely, for busting in a cycle, I should slap my hands, but I didn’t think of another way.
And the problem with the code is that if instead of $idmark we immediately put a value (in our case, 44), or instead of $smodel we substitute "Caliber" in the condition, then the condition will work and $idmodel will be assigned.
And if you leave the code as is, the condition does not work.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Viktor Vsk, 2015-04-24
@hzs

I didn’t quite understand what to substitute where and what doesn’t work if you don’t touch anything, but with the help of xpath you can do this:
//sModel[../idModel='2986' and ../idMark='44']

A
Alexander Nisel, 2015-04-24
@hzs

As a result, the solution of the problem was reduced to one line of code:

echo $idref->xpath('//idModel[../sModel="' . $smodel . '" and ../idMark=' . $idmark . ']')[0];

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question