Home > other >  PHP xml_parse with XPATH returns empty array for specific element value
PHP xml_parse with XPATH returns empty array for specific element value

Time:11-04

The goal is to pull all the data for a single product that contains a predefined code out of a huge xml file. It does look like I am getting the selected product, but the result array is empty.

This is a part of the xml file and the function that returns $result as an empty array.:

<ROOT>
<Products>
<Product>
     <ProductName><![CDATA[Draining Tube Universal Retail]]></ProductName>
     <ProductCode><![CDATA[476521Az-f]]></ProductCode>
     <Category><![CDATA[Bathing]]></Category>
     <Price>18.000030</Price>
     <AvailableQty>9</AvailableQty>
     <Condition>New</Condition>
     <ProductAttributes><Brand>Bbrand name</Brand></ProductAttributes>
     <Location></Location>
     <ImageURL><![CDATA[https:url here]]></ImageURL>
     <ShippingProductClass></ShippingProductClass>
     <ProductSummary><![CDATA[Universal Retail Box Out of Box failure Warranty]]></ProductSummary>
     <ProductDescription><![CDATA[<p>Very easy to install<br />&#8226; Full instructions provided</p>]]></ProductDescription>
     <LenghtCM><![CDATA[101.2]]></LenghtCM> 
     <WidthCM><![CDATA[48.95]]></WidthCM> 
     <HeightCM><![CDATA[36.3]]></HeightCM> 
     <MassKG><![CDATA[1.925]]></MassKG> 
    </Product>
</Products>
</ROOT>

Here is the code:

$refsku = '476521Az-f';

$xml=file_get_contents( $cache_url_use );
$xml_parse = simplexml_load_string($xml, null, LIBXML_NOCDATA);

$results = $xml_parse->xpath("/ROOT/Products/Product[@ProductCode= " . $refsku . " ]");

echo "<br><pre>"; print_r($results); echo "</pre>";

CodePudding user response:

I believe your problem is that the XPath you are generating looks like this:

/ROOT/Products/Product[@ProductCode= 476521Az-f ]

That token 476521Az-f will I think cause an error. It starts off looking like a numeric literal, but the Az breaks that. It can't be interpreted as the name of an element <476521Az-f/> because an element name can't start with a digit.

I think the solution is to ensure your XPath puts quotes around that string, e.g.

/ROOT/Products/Product[@ProductCode= '476521Az-f' ]

or

/ROOT/Products/Product[@ProductCode= "476521Az-f" ]

e.g.

$results = $xml_parse->xpath("/ROOT/Products/Product[@ProductCode='" . $refsku . "']");
  • Related