Skip to content
Advertisement

How can I show XML external entities in a php page?

I am currently working on a little library project using XML to define books, and php to do a search using title/author then showing that specific book in the browser. So I made a bunch of books in XML files, then linked those files as external entities in my main XML file. I used a DTD to define the entities, and a XSD file to define the scheme for my xml file (I am required to use the XSD, but it doesn’t let me define entities so I made a DTD too). All the files were validated, and when showing a single book, or if I put all the books in the same xml file without using entities, it works just fine. But when I try using the main xml file that contain just entities, It doesn’t recognize them, and gives me the following warnings without showing anything:

Warning: simplexml_load_file(): test.xml:6: parser error : Entity ‘book1’ not defined in C:xampphtdocsxmltest.php on line 14

Warning: simplexml_load_file(): &book1; in C:xampphtdocsxmltest.php on line 14

My php script is the following :

JavaScript

And my main XML is like this (with that &book repeating for each of my books):

JavaScript

Following are the DTD:

JavaScript

And XSD:

JavaScript

And finally, here is a sample of my book.xml:

JavaScript

PS: I am using xampp to run php on browser.

EDIT : after some tests, I came to understand that the way I store the file, it just shows everything it contains and doesn’t read it like I do, I tried running the php in a cmd prompt and I could see that it prints the xml file as it is, so I guess I should find a way to specify how it should interpret the xml file content.

EDIT 2: I changed to simpleXML , now I can show the books infos as I want , but I can’t figure out how to show the entities content.

Advertisement

Answer

Well I found a solution to my problem , I had to use the SimpleXMLElement attribute and some libxml options in the simplexml_load_file function , like this:

JavaScript

The first one LIBXML_DTDLOAD Load the external subset and the second LIBXML_NOENT Substitute entities as stated in the official documentation : https://www.php.net/manual/en/libxml.constants.php .

NB: to use multiple LIBXML constants you should separate them by a pipe. (Thanks to the first note in this documentation : https://www.php.net/manual/en/function.simplexml-load-string.php#101594 )

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement