0

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>
3
  • 1
    What error are you getting exactly? Commented Apr 21, 2014 at 12:55
  • have you tried addslashes function before parsing? Commented Apr 21, 2014 at 12:58
  • yes I tried addslashes finction Commented Apr 21, 2014 at 13:17

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

4 Comments

Its still giving error on this line $xmlObj = simplexml_load_string($xml);
sorry getting error due to **&**<client_name>Knapp & Donut Shop</client_name>
The XML is invalid. The & must be encoded correctly.
Updated my answer with a conversion line: $xml = str_replace(array("&amp;", "&"), array("&", "&amp;"), $xml);

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.