0

I want to print parent node attributes if Item is found. I am using XPath, PHP and XML. My code is

if( ! $xml = simplexml_load_file($my_feed) ) 
        { 
            echo 'unable to load XML file'; 
        } 
        else 
        { 
            $nodes = $xml->xpath("//Stock/Assortment[contains(translate(Item, 'АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЬЫЭЮЯ', 'абвгдеёжзиёклмнопрстуфхцчшщьыэюя'), '$search_phrase')]|/Stock/@City | /Stock/@CompanyName | /Stock/@Address | /Stock/@Date");
            foreach($nodes as $node)
            {
                if(strpos($node->Item,$search_phrase) !== false)
                {
                print $node->City.$node->CompanyName.$node->Address.$node->Date;
                }
                print $node->Item."\r\n".$node->Price."\r\n".$node->ValidDate."\r\n".$node->Manufacturer."\r\n"."<br/>";
            } 
        }

And it is not printing attributes of parent node, what is the problem? My xml is:

<?xml version="1.0" encoding="utf-8"?>
<Stock City="Душанбе" CompanyName="Фирик и ко" Address="Ленина 2" Date="12.06.2014 06:22:58">
  <Assortment>
    <ID>1</ID>
    <Item>3В амп.  №3 ( Витамины В1+В6+В12 )</Item>
    <Quantity>8</Quantity>
    <Price>17.0000</Price>
    <ValidDate>01.01.1999</ValidDate>
    <Summ>136.0000</Summ>
    <Manufacturer>Заглушка</Manufacturer>
    <Supplier>Заглушка</Supplier>
  </Assortment>
</Stock>
Satish Sharma
  • 9,547
  • 6
  • 29
  • 51
Firdavs Kurbonov
  • 1,252
  • 4
  • 16
  • 42

1 Answers1

0

As you check for the search phrase both in the xpath as well as in the foreach loop, you can drop it from one of the places - if it counts in your eyes as wrong doing - I'd say it does.

Another thing you do wrong is that you union the attributes to the element which really makes no sense if you want to have a distinct and non-complex to deal-with xpath result. So I'd say you're doing that wrong, you perhaps should do multiple xpath queries here instead (most likely, you should do that).

So what else seems wrong? Then indentation of your code is for sure done wrong. If you really write your code that un-loveley, for sure you're doing many mistakes because your code is just unnecessarily hard to read and decypher.

So that's really wrong, because as the code is hard to follow I might give you wrong what's wrong with your code wrongs here, so it's wrong for sure to do so.

Then you actually don't check if the xpath returns the attributes or not. So that's really wrong with your question. You should have checked that before asking.

Next to that - and again really wrong with your question is the point that you don't look for error messages. If you would have done that, you would have already known what's wrong with your code. I'll close it against the duplicate that has information on how to get better error messages.

hakre
  • 193,403
  • 52
  • 435
  • 836