Page 1 of 1

PHP xpath query

Posted: Mon Dec 01, 2014 9:58 pm
by shrichavda
Hi ,
I have an xml file which i use to retrieve product information from. I am able to get most of the data that i require except for its Specs. here is the part of php code. This php file was developed by another developer and it is bit broken so i have to fix it.

Code: Select all

$products = $xml->xpath('//PRV');
foreach ($products as $product) {
       
          $stats = getstats($product->xpath('//PRAT'));
          $statskeys = array_keys($stats);

         function getstats($stats)
		{
		$statsarray ="";
			foreach ($stats as $PRAT) {
				$statsarray[$PRAT['dictionary_entry']] = $PRAT->VALUE . " " .       $PRAT->VALUE['unit'];
			return $statsarray;
		}
             }
}
this code does not do anything really. I wish to echo the weight's value and unit from to below xml.

Code: Select all

<PRV proid="100403" id="328928" name="1.347-705.0  WD 4.200">
<PRAT languagespecific="0" attrtype="ProductattributeTypeTechData" datatype="N" ProdID="328928" name="GEWICHT_OHNE_ZUBEHOER" product_number="13477050" dictionary_entry="Weight" dict_id="1911">
<VALUE nr="1" unit="kg" unit_id="3123" vo="" vo_id="">7,5</VALUE>
</PRAT>
</PRV>

Re: PHP xpath query

Posted: Mon Dec 01, 2014 10:07 pm
by shrichavda
If i print the array keys
print_r(array_keys($stats));

it shows
Array ( [0] => )

Re: PHP xpath query

Posted: Mon Dec 01, 2014 10:17 pm
by requinix
1. It will fatal because the function is defined in a loop, which is among other things a bad idea. At least it should - I have no idea why yours is working, assuming you posted your code exactly as you have it and didn't try to alter or modify it for posting. Move it outside the loop and before all this code.
2. PHP will spit out a warning if you run the code and follow the proper development practices of showing all errors and warnings:
Warning: Illegal offset type in <file> on line <line>
The line in question is

Code: Select all

$statsarray[$PRAT['dictionary_entry']] = $PRAT->VALUE . " " . $PRAT->VALUE['unit'];
Rule #1a about SimpleXML is that everything is an object. Even attributes. That means $PRAT[dictionary_entry] is an object and you can't use objects as array keys.
Rule #1b about SimpleXML is that if you have a problem then casting to a string will probably fix it.