Hi,

I'm having problem with reading xml file because there are invalid chars like & sign. How can I evaluate this problem and read the file with simple_xml or DOM?

php

$xmlDoc=simplexml_load_file('items.xml');

$doc = new DomDocument;
$doc->load('items.xml');

//Both of these don't work

xml

<?xml version="1.0" encoding="ISO-8859-1"?>

<store id="AMZ-0101-STR">
    <items>
        <item>
            <id>1111</id>
            <title>Apple iPhone 4 16GB on Three (3) Network</title>
            <description>iPhone 4. The fastest, highest-resolution iPhone
While everyone else was busy trying to keep up with iPhone, Apple were busy creating amazing new features that make iPhone more powerful, easier to use, and more indispensable than ever. The result is iPhone 4.

FaceTime
iPhone 4 makes video calling a reality. With just a tap you can wave hello to your kids, share a smile from across the globe or watch your best friend laugh at your stories - iPhone 4 to iPhone 4 or to the new iPod touch over Wi-Fi. And it works right out of the box. No other phone makes staying in touch this much fun.

Retina Display
The Retina display on iPhone 4 is the sharpest, highest-resolution phone screen ever, with four times the pixel count of previous iPhone models. In fact, the pixel density is so high that the human eye is unable to distinguish individual pixels, which makes text amazingly crisp and images stunningly sharp.

Multitasking
iPhone 4 introduces a whole new way of multitasking. Now you can run your favourite third-party apps and switch between them instantly without slowing down the performance of the foreground app or draining the battery unnecessarily.

HD Video Recording and Editing
Shoot your own films in high definition. Capture impressive video even in low-light settings, thanks to the advanced backside illumination sensor and built-in LED light. Then edit and create your own mini-masterpiece right on iPhone 4 using the new iMovie app - with Apple-designed themes, titles and transitions. It's now available on the App Store.

5-Megapixel Camera with LED Flash
Take detailed photos with the new 5-megapixel camera with built-in LED flash. The advanced backside illumination sensor captures great pictures even in low light and the new front-facing camera makes it easy to take self-portraits.</description>
            <url>http://www.amazon.co.uk/gp/product/B005MG8O96/ref=olp_product_details?ie=UTF8&me=&seller=</url>
            <price>85.56</price>
            <stock>Yes</stock>
            <timestamp>11/07/2012 21:15</timestamp>
            <images>
                <image>http://ecx.images-amazon.com/images/I/51e-Yh0Ls%2BL._SL500_AA300_.jpg</image>
                <image>http://ecx.images-amazon.com/images/I/41ccNRHKVcL._SL500_AA300_.jpg</image>
                <image>http://ecx.images-amazon.com/images/I/61kHQbi5NiL.jpg</image>
            </images>
        </item>
        <item>
            <id>2222</id>
            <title>Nokia Lumia 900 Smartphone</title>
            <description>The Nokia lumia 900 is a beautiful slim smartphone designed equally for work and pleasure. With Corning® Gorilla® Glass as standard this phone will be protected from scratches and the day to day abuses you throw at it.

It has a wonderful large 4.3" AMOLED ClearBlack glass touchscreen display and all day battery life, so conversations will never be cut short. With a 1400 MHz Qualcomm processor on board and internet explorer 9, you're guaranteed a speedy performance whether you are surfing the web, on facebook or simply writing emails.

The whole thing runs on the Windows phone 7.5 operating system, and includes great productivity tools like Office Applications (Excel, Word, Powerpoint, One Note) so you can carry on with business, even on the move. 

The other great feature of the mobile phone is its 8 megapixel digital camera with Carl Zeiss optics, allowing you to take amazingly clear photos wherever you are, whenever you want. 

The Nokia Lumia 900 also has a 1 megapixel front facing camera and Tango Video calls software installed. This amazing feature will allow you to make and receive video calls over Wi-Fi from anyone who also has Tango installed.</description>
            <url>http://www.misco.co.uk/productinfo/productinfo?productCode=194614&affiliate=2008&cm_mmc=CSE-_-pricerunner-_-networking%20&%20Communications-_-194614</url>
            <price>469.99</price>
            <stock>Yes</stock>
            <timestamp>01/02/2012 11:00</timestamp>
            <images>
                <image>http://img.misco.eu/resources/images/products/106/NOK/A0/A00005978//A00005978_1600x1600.jpg</image>
            </images>
        </item>
        <item>
            <id>3333</id>
            <title>Nokia C2-01</title>
            <description>This beautifully designed Windows Phone has a sleek large 3.7" touchscreen with Corning® Gorilla® Glass technology. This will protect your investment from the abuses of daily life. It is tough and scratch resistant so a perfect addition to your new smartphone. The screen is also anti-glare so it’s easy to see, even in the sun. 

The Lumia 710 is a lightweight and slim multimedia mobile phone that is ready for business and pleasure. With Office 365 installed you have mobile access to all your emails, calendar, contacts and shared documents where ever you are. Added features like Sharepoint and Skydrive let you keep you files in a secure place and share them with colleagues. You can even work with them offline and save them when you’re connected again. 

This smartphone also has a 5 megapixel digital camera so you can take high quality photos whenever you want, or record HD video's and share them with the world in seconds. 

This phone can be personalised to suit your needs with exchangeable back covers to suit your mood, or by downloading any of the thousands of available applications. 

That’s not all. This smartphone runs on the Windows Mango operating system, so it’s also quick. It also has fast web browsing thanks to Internet Explorer 9. 

With all these features you need storage and the Nokia Lumia 710 gives you up to 8GB of it. Save all of your photos, videos, music and more, and if that's not enough you can also listen to the built-in MP3 player or FM radio, and you will never get lost thanks to the integrated Sat Nav system.</description>
            <url>http://www.misco.co.uk/productinfo/productinfo?productCode=192510&affiliate=2008&cm_mmc=CSE-_-pricerunner-_-networking%20&%20Communications-_-192510</url>
            <price>69.99</price>
            <stock>No</stock>
            <timestamp>01/02/2012 11:00</timestamp>
            <images>
                <image>http://img.misco.eu/resources/images/products/106/NOK/00/0020C63//0020C63_1600x1600.jpg</image>
                <image>http://img.misco.eu/resources/images/products//106/NOK/00/0020C63/0020C63_15_1600x1600.jpg</image>
                <image>http://img.misco.eu/resources/images/products//106/NOK/00/0020C63/0020C63_7_1600x1600.jpg</image>
                <image>http://img.misco.eu/resources/images/products//106/NOK/00/0020C63/0020C63_9_1600x1600.jpg</image>
                <image>http://img.misco.eu/resources/images/products//106/NOK/00/0020C63/0020C63_1_1600x1600.jpg</image>
                <image>http://img.misco.eu/resources/images/products//106/NOK/00/0020C63/0020C63_13_1600x1600.jpg</image>
                <image>http://img.misco.eu/resources/images/products//106/NOK/00/0020C63/0020C63_8_1600x1600.jpg</image>
            </images>
        </item>
    </items>
</store>

An & in XML should have been escaped with &amp;, so technically it is invalid. You can try to replace it before loading.

Code below gives this error:

ERROR

Warning: simplexml_load_file() [function.simplexml-load-file]: I/O warning : failed to load external entity "<?xml version="1.0" encoding="ISO-8859-1"?> <store id="AMZ-0101-STR"> <items> <item> <id>1111</id> <title>Apple iPhone 4 16GB on Three (3) Network</title> <description>iPhone 4. The fastest, highest-resolution iPhone While everyone else was busy trying to keep up with iPhone, Apple were busy creating amazing new features that make iPhone more powerful, easier to use, and more indispensable than ever. The result is iPhone 4. FaceTime iPhone 4 makes video calling a reality. With just a tap you can wave hello to your kids, share a smile from across the globe or watch your best friend laugh at your stories - iPhone 4 to iPhone 4 or to the new iPod touch over Wi-Fi. And it works right out of the box. No other phone makes staying in touch this much fun. Retina in C:\wamp\www\TEST\xml\index.php on line 10

CODE

<?php
$file = "items.xml";

$file_content = @file_get_contents($file);

if (! $file_content) { exit('error'); }

$file_content = str_replace('&', '&amp;', $file_content);

$xmlDoc=simplexml_load_file($file_content);

echo '<pre>'; print_r($xmlDoc);
?>

While waiting for your answer I learned that wrapping the content with CDATA solves the problem. However, do you think using simplexml_load_string() is better than CDATA? I'm asking because XML file looks ugly now with CDATA tags.

Note: The external file I'll reading is going to be a massive file. Would the string variable handle it?

Well, adding the CDATA makes it valid XML, so IMO that is the better option. The other option is to replace the special characters.

OK I updated but I'm stil getting error with this DTD. If title, description, url and image tags possibly have invalid chars so how do I avoid it?

<?xml version="1.0" encoding="ISO-8859-1"?>

<!-- Document Type Definition -->

<!DOCTYPE store [

<!ELEMENT store (timestamp,items)>
<!ELEMENT items (item+)>
<!ELEMENT item (title,description,url,price,images)>
<!ELEMENT images (image+)>

<!ELEMENT title (#PCDATA)>
<!ELEMENT description (#PCDATA)>
<!ELEMENT url (#PCDATA)>
<!ELEMENT image (#PCDATA)>

<!ATTLIST store id CDATA #REQUIRED>
<!ATTLIST item id CDATA #REQUIRED>
<!ATTLIST item available (Yes|No) #REQUIRED>
]>

<!-- Extensible Markup Language -->

<store id="AMZ-0101-STR">
    <timestamp>01/02/2012 11:00</timestamp>
    <items>
        <item id="1111" available="Yes">
            <title>Apple iPhone 4 16GB on Three (3) Network</title>
            <description>iPhone 4. The fastest, highest-resolution iPhone
    While everyone else was busy trying to keep up with iPhone, Apple were busy creating amazing new features that make iPhone more powerful, easier to use, and more indispensable than ever. The result is iPhone 4.

    FaceTime
    iPhone 4 makes video calling a reality. With just a tap you can wave hello to your kids, share a smile from across the globe or watch your best friend laugh at your stories - iPhone 4 to iPhone 4 or to the new iPod touch over Wi-Fi. And it works right out of the box. No other phone makes staying in touch this much fun.

    Retina Display
    The Retina display on iPhone 4 is the sharpest, highest-resolution phone screen ever, with four times the pixel count of previous iPhone models. In fact, the pixel density is so high that the human eye is unable to distinguish individual pixels, which makes text amazingly crisp and images stunningly sharp.

    Multitasking
    iPhone 4 introduces a whole new way of multitasking. Now you can run your favourite third-party apps and switch between them instantly without slowing down the performance of the foreground app or draining the battery unnecessarily.

    HD Video Recording and Editing
    Shoot your own films in high definition. Capture impressive video even in low-light settings, thanks to the advanced backside illumination sensor and built-in LED light. Then edit and create your own mini-masterpiece right on iPhone 4 using the new iMovie app - with Apple-designed themes, titles and transitions. It's now available on the App Store.

    5-Megapixel Camera with LED Flash
    Take detailed photos with the new 5-megapixel camera with built-in LED flash. The advanced backside illumination sensor captures great pictures even in low light and the new front-facing camera makes it easy to take self-portraits.</description>
            <url>http://www.amazon.co.uk/gp/product/B005MG8O96/ref=olp_product_details?ie=UTF8&me=&seller=</url>
            <price>85.56</price>
            <images>
                <image>http://ecx.images-amazon.com/images/I/51e-Yh0Ls%2BL._SL500_AA300_.jpg</image>
                <image>http://ecx.images-amazon.com/images/I/41ccNRHKVcL._SL500_AA300_.jpg</image>
                <image>http://ecx.images-amazon.com/images/I/61kHQbi5NiL.jpg</image>
            </images>
        </item>
        <item id="2222" available="Yes">
            <title>Nokia Lumia 900 Smartphone</title>
            <description>The Nokia lumia 900 is a beautiful slim smartphone designed equally for work and pleasure. With Corning® Gorilla® Glass as standard this phone will be protected from scratches and the day to day abuses you throw at it.

    It has a wonderful large 4.3" AMOLED ClearBlack glass touchscreen display and all day battery life, so conversations will never be cut short. With a 1400 MHz Qualcomm processor on board and internet explorer 9, you're guaranteed a speedy performance whether you are surfing the web, on facebook or simply writing emails.

    The whole thing runs on the Windows phone 7.5 operating system, and includes great productivity tools like Office Applications (Excel, Word, Powerpoint, One Note) so you can carry on with business, even on the move. 

    The other great feature of the mobile phone is its 8 megapixel digital camera with Carl Zeiss optics, allowing you to take amazingly clear photos wherever you are, whenever you want. 

    The Nokia Lumia 900 also has a 1 megapixel front facing camera and Tango Video calls software installed. This amazing feature will allow you to make and receive video calls over Wi-Fi from anyone who also has Tango installed.</description>
            <url>http://www.misco.co.uk/productinfo/productinfo?productCode=194614&affiliate=2008&cm_mmc=CSE-_-pricerunner-_-networking%20&%20Communications-_-194614</url>
            <price>469.99</price>
            <images>
                <image>http://img.misco.eu/resources/images/products/106/NOK/A0/A00005978//A00005978_1600x1600.jpg</image>
            </images>
        </item>
        <item id="3333" available="No">
            <title>Nokia C2-01</title>
            <description>This beautifully designed Windows Phone has a sleek large 3.7" touchscreen with Corning® Gorilla® Glass technology. This will protect your investment from the abuses of daily life. It is tough and scratch resistant so a perfect addition to your new smartphone. The screen is also anti-glare so it’s easy to see, even in the sun. 

    The Lumia 710 is a lightweight and slim multimedia mobile phone that is ready for business and pleasure. With Office 365 installed you have mobile access to all your emails, calendar, contacts and shared documents where ever you are. Added features like Sharepoint and Skydrive let you keep you files in a secure place and share them with colleagues. You can even work with them offline and save them when you’re connected again. 

    This smartphone also has a 5 megapixel digital camera so you can take high quality photos whenever you want, or record HD video's and share them with the world in seconds. 

    This phone can be personalised to suit your needs with exchangeable back covers to suit your mood, or by downloading any of the thousands of available applications. 

    That’s not all. This smartphone runs on the Windows Mango operating system, so it’s also quick. It also has fast web browsing thanks to Internet Explorer 9. 

    With all these features you need storage and the Nokia Lumia 710 gives you up to 8GB of it. Save all of your photos, videos, music and more, and if that's not enough you can also listen to the built-in MP3 player or FM radio, and you will never get lost thanks to the integrated Sat Nav system.</description>
            <url>http://www.misco.co.uk/productinfo/productinfo?productCode=192510&affiliate=2008&cm_mmc=CSE-_-pricerunner-_-networking%20&%20Communications-_-192510</url>
            <price>69.99</price>
            <images>
                <image>http://img.misco.eu/resources/images/products/106/NOK/00/0020C63//0020C63_1600x1600.jpg</image>
                <image>http://img.misco.eu/resources/images/products//106/NOK/00/0020C63/0020C63_15_1600x1600.jpg</image>
                <image>http://img.misco.eu/resources/images/products//106/NOK/00/0020C63/0020C63_7_1600x1600.jpg</image>
                <image>http://img.misco.eu/resources/images/products//106/NOK/00/0020C63/0020C63_9_1600x1600.jpg</image>
                <image>http://img.misco.eu/resources/images/products//106/NOK/00/0020C63/0020C63_1_1600x1600.jpg</image>
                <image>http://img.misco.eu/resources/images/products//106/NOK/00/0020C63/0020C63_13_1600x1600.jpg</image>
                <image>http://img.misco.eu/resources/images/products//106/NOK/00/0020C63/0020C63_8_1600x1600.jpg</image>
            </images>
        </item>
    </items>
</store>

Encode those that need encoding:

"   &quot;
'   &apos;
<   &lt;
>   &gt;
&   &amp;

Encoding with <!ENTITY & "&amp;"> and others doesn't work or I'm crap!

I'm stuck.

The data in the XML needs those characters encoded. I don't think it is possible to specify to do so using the DTD. You will have to encode the data yourself.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.