Question

I trying to parse XML file but getting parsing error.

Code ::

$xmlUrl = 'products.xml';
$xmlStr = file_get_contents($xmlUrl); 
$xmlObj = simplexml_load_string($xmlStr);

XML file ::

<?xml version="1.0" encoding="UTF-8"?>
<result>
    <orderlist>
            <order_no>123123</order_no>
            <date></date>
            <client_name>Knapp's Donut Shop</client_name>
            <sector>54</sector>
    </orderlist>
</result>

I am getting error because of this tag

<client_name>Knapp's Donut Shop</client_name>
Was it helpful?

Solution

The conversion to a SimpleXML Object and the output works, see code example below. Check your "products.xml" file for the correct UTF-8 encoding type.

<?php

$xml = <<< XML
<?xml version="1.0" encoding="UTF-8"?>
<result>
    <orderlist>
            <order_no>123123</order_no>
            <date></date>
            <client_name>Knapp & Donut Shop</client_name>
            <sector>54</sector>
    </orderlist>
</result>
XML;

$xml = str_replace(array("&amp;", "&"), array("&", "&amp;"), $xml);

$xmlObj = simplexml_load_string($xml);

var_dump($xmlObj);

echo PHP_EOL . $xmlObj->orderlist->client_name;

// Result: Knapp & Donut Shop
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top