0

Im trying to get the catId value. But i can see only the category value.

My xml file looks below:

<sample>
    <Item ItemNumber="00000088" FormattedItemNumber="00000-088">
      <CompatibleModels />
        <Category CatId="160" >  test 123 </Category>
      <Images />
      <Documents />
      <RequiredItems />
    </Item>
</sample>

$xml = simplexml_load_file("test.xml");
print_r($xml);

[sample] => Array
        (
            [0] => SimpleXMLElement Object
                (
                    [@attributes] => Array
                        (
                            [ItemNumber] => 00000088
                            [FormattedItemNumber] => 00000-088
                        )

                    [Category] =>   Bags/Luggage 123 
                )

how can get the CatId value? Why the cateId value is missing?

Mohan
  • 85
  • 5
  • You should get familiar with [simplexml and all its methods](https://www.php.net/manual/en/book.simplexml.php). Just to put you on track: `print_r($xml->sample[0]->Item->Category->attributes()->CatId);`. And please go over [How to create a Minimal, Reproducible Example](https://stackoverflow.com/help/reprex) because yours is not (missing the xml root element and the other samples in there). – Zeitounator May 15 '19 at 16:10
  • Possible duplicate of [Getting actual value from PHP SimpleXML node](https://stackoverflow.com/questions/1133931/getting-actual-value-from-php-simplexml-node) – miken32 May 18 '19 at 05:14

3 Answers3

1

You can loop and get it by using following snippet, please refer inline documentation for explanation

$xml1 = simplexml_load_file("test.xml") or die("Error: Cannot create object");
foreach ($xml1->children() as $items1) { // children mean item
    echo ($items1->category['catid']); // for category tag get catid attribute
}
Rahul
  • 18,271
  • 7
  • 41
  • 60
1

print_r doesn't really work with SimpleXML objects. But from the sample data you have provided you can simply access the CatId attribute using

echo $xml->Item->Category['CatId'];
Nick
  • 138,499
  • 22
  • 57
  • 95
1

You can do it by many ways. Let's try-

foreach ($xml as $items) {
    echo $items->Category['CatId'];
}

WORKING DEMO: https://3v4l.org/Onqe2

A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103