Ошибка failed to load external entity

I’m trying to create a small application that will simply read an RSS feed and then layout the info on the page.

All the instructions I find make this seem simplistic but for some reason it just isn’t working. I have the following

include_once(ABSPATH.WPINC.'/rss.php');
$feed = file_get_contents('http://feeds.bbci.co.uk/sport/0/football/rss.xml?edition=int');
$items = simplexml_load_file($feed);

That’s it, it then breaks on the third line with the following error

Error: [2] simplexml_load_file() [function.simplexml-load-file]: I/O warning : failed to load external entity "<?xml version="1.0" encoding="UTF-8"?> <?xm
The rest of the XML file is shown.

I have turned on allow_url_fopen and allow_url_include in my settings but still nothing.
I’ve tried multiple feeds that all end up with the same result?

I’m going mad here

asked Feb 9, 2014 at 16:22

Gavin Mannion's user avatar

Gavin MannionGavin Mannion

8751 gold badge14 silver badges32 bronze badges

2

simplexml_load_file() interprets an XML file (either a file on your disk or a URL) into an object. What you have in $feed is a string.

You have two options:

  • Use file_get_contents() to get the XML feed as a string, and use e simplexml_load_string():

    $feed = file_get_contents('...');
    $items = simplexml_load_string($feed);
    
  • Load the XML feed directly using simplexml_load_file():

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

answered Feb 9, 2014 at 16:28

Amal Murali's user avatar

Amal MuraliAmal Murali

75.3k18 gold badges128 silver badges150 bronze badges

1

You can also load the content with cURL, if file_get_contents insn’t enabled on your server.

Example:

$ch = curl_init();  

curl_setopt($ch,CURLOPT_URL,"http://feeds.bbci.co.uk/sport/0/football/rss.xml?edition=int");
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);

$output = curl_exec($ch);

curl_close($ch);

$items = simplexml_load_string($output);

answered Aug 14, 2014 at 20:58

Herlon Aguiar's user avatar

this also works:

$url = "http://www.some-url";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$xmlresponse = curl_exec($ch);
$xml=simplexml_load_string($xmlresponse);

then I just run a forloop to grab the stuff from the nodes.

like this:`

for($i = 0; $i < 20; $i++) {
$title = $xml->channel->item[$i]->title;
$link = $xml->channel->item[$i]->link;
$desc = $xml->channel->item[$i]->description;
$html .="<div><h3>$title</h3>$link<br />$desc</div><hr>";
}
echo $html;

***note that your node names will differ, obviously..and your HTML might be structured differently…also your loop might be set to higher or lower amount of results.

answered Apr 30, 2015 at 3:58

$url = 'http://legis.senado.leg.br/dadosabertos/materia/tramitando';
$xml = file_get_contents("xml->{$url}");
$xml = simplexml_load_file($url);

answered Nov 11, 2016 at 16:50

Antonio Junior's user avatar

2

If you see the following error/warning when using the simplexml_load_file() function:

Warning: simplexml_load_file(): I/O warning : failed to load external entity "..." in /path/to/file.php on line ...

Then it means that you have likely provided the XML you wish to load from a file as a string to the simplexml_load_file() function argument (instead of the path to that XML file). It could, for example, happen in the following case:

$xmlStr = file_get_contents('/path/to/file.xml');
$xml = simplexml_load_file($xmlStr);
// ...

In the example above, using the file_get_contents() function returns a string of loaded XML. When you provide that as an argument to the simplexml_load_file() function, it throws a warning because it is expecting the path of the XML file as an argument and not a string. To solve this, you can do any of the following:

  • Use the XML String With SimpleXMLElement Object Instance;
  • Load the XML File Directly With simplexml_load_file()
  • Use the XML String With simplexml_load_string().

Use the XML String With SimpleXMLElement Object Instance

You could, for example, use file_get_contents() to first load the XML file into a string, and then provide that as an argument to the SimpleXMLElement object instance. For example:

$xmlStr = file_get_contents('/path/to/file.xml');
$xml = new SimpleXMLElement($xmlStr);
// ...

Load the XML File Directly With simplexml_load_file()

You could directly provide the XML file path to the simplexml_load_file() function, and it will return a SimpleXMLElement object instance on success (and false on failure). For example:

$xml = simplexml_load_file('/path/to/file.xml');
// ...

Use the XML String With simplexml_load_string()

You could, for example, use file_get_contents() to first load the XML file into a string, and then provide that as an argument to the simplexml_load_string() function — which would interpret the string of XML into a SimpleXMLElement object instance on success (and return false on failure). For example:

$xmlStr = file_get_contents('/path/to/file.xml');
$xml = simplexml_load_string($xmlStr);
// ...

Hope you found this post useful. It was published 26 Aug, 2022. Please show your love and support by sharing this post.

This issue was moved to a discussion.

You can continue the conversation there.

Go to discussion →

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.

Already on GitHub?
Sign in
to your account

Comments

@happypennygames

I am attempting to perform local validation of a musicxml file exported using musescore (uncompressed xml). I’m using xmllint.js (https://github.com/kripken/xml.js/blob/master/xmllint.js) on a simulated client side using a python server. The validation pipeline works great with other xsd/xml pairs, but I get this error when I substitute musicxml.xsd for the schema (has nothing to do with the xml file itself).

warning: failed to load external entity "http://www.musicxml.org/xsd/xlink.xsd"
file_0.xsd:26: element import: Schemas parser warning : Element '{http://www.w3.org/2001/XMLSchema}import': Failed to locate a schema at location 'http://www.musicxml.org/xsd/xml.xsd'. Skipping the import.
warning: failed to load external entity "http://www.musicxml.org/xsd/xlink.xsd"
file_0.xsd:27: element import: Schemas parser warning : Element '{http://www.w3.org/2001/XMLSchema}import': Failed to locate a schema at location 'http://www.musicxml.org/xsd/xlink.xsd'. Skipping the import.
file_0.xsd:2248: element attribute: Schemas parser error : attribute use (unknown), attribute 'ref': The QName value '{http://www.w3.org/XML/1998/namespace}lang' does not resolve to a(n) attribute declaration.

I copied the full zip of all the files into the same place as the musicxml.xsd fiile.

The instructions in musicxml.xsd reference the catalog.xml file, but I do not reference it (I’m not sure how), so i don’t know if that’s the problem. I’m also ok with manually pasting all the other xsd files into the musicxml.xsd file if there was way to do that.

Modifying the musicxml.xsd file such that the schema location is just the file name, and running:

xmllint --schema musicxml.xsd t1.musicxml --noout --nonet

actually does validate at the command line in a linux terminal, which implies the fault is in some interaction of the import statement with xmllint.js at this point. Feel free to close the issue if no suggestions given this update.

@mdgood

@happypennygames This page has instructions for using XML catalogs with lxml in Python. It sounds like this should work for your situation and is better than modifying the MusicXML schema files:

https://lxml.de/resolvers.html

Please let us know if this works for you.

@happypennygames

Thanks for posting! I did look at it as soon as you replied- unfortunately, couldn’t make out how to use it. I will try for a deeper look this weekend and let you know my specific questions.

@happypennygames

@apacha

Hi,
I’ve stumbled upon this problem too after upgrading to MusicXML Schema 4.0 DTD and I don’t really see how the mentioned catalogues could solve the issue. I’m executing this very simple code, just trying to parse the schema:

from lxml import etree

schema_file_name: str = 'utils/data_files/musicxml.xsd'
schema = etree.XMLSchema(file=schema_file_name)

and I already get the following error:

Traceback (most recent call last):
  File "/Users/alex/musicxml_validation.py", line 5, in <module>
    schema = etree.XMLSchema(file=schema_file_name)
  File "src/lxml/xmlschema.pxi", line 88, in lxml.etree.XMLSchema.__init__
lxml.etree.XMLSchemaParseError: attribute use (unknown), attribute 'ref': The QName value '{http://www.w3.org/XML/1998/namespace}lang' does not resolve to a(n) attribute declaration., line 2247

which makes me question whether the schema can be used like that (by lxml) at all. For parsing the schema, there is no option for any catalog-resolver or the like.

Can you shed some light on this?

@mdgood

@david-pace

I just ran into the same issue when importing the MusicXML 4.0 XSD using the Eclipse Modeling Framework (EMF). If you’re interested in some background information, you can read my blog post.

The error messages indicate that the schema locations of the following XSD imports (lines 26 and 27 of musicxml.xsd in the current 4.0 release) can not be resolved:

<xs:import namespace="http://www.w3.org/XML/1998/namespace" schemaLocation="http://www.musicxml.org/xsd/xml.xsd"/>
<xs:import namespace="http://www.w3.org/1999/xlink" schemaLocation="http://www.musicxml.org/xsd/xlink.xsd"/>

When browsing the URLs directly in a browser the XSDs are reachable, but there is a HTTP -> HTTPS redirection (e.g. from http://www.musicxml.org/xsd/xml.xsd to https://www.musicxml.org/xsd/xml.xsd); also my browser (Firefox) indicates that the connection is not safe for some reason. Probably the HTTPS redirection, the SSL certificate or both cause problems while resolving the XSD imports.

My solution was to replace the URLs with the following ones:

https://www.musicxml.com/xsd/xml.xsd
https://www.musicxml.com/xsd/xlink.xsd

With those schema locations the MusicXML XSD could be loaded without any problems. Consequently one solution could be to use https:// URLs in future versions.

@w3c
w3c

locked and limited conversation to collaborators

Feb 15, 2022

This issue was moved to a discussion.

You can continue the conversation there.

Go to discussion →

koza4ok

632 / 440 / 67

Регистрация: 19.09.2012

Сообщений: 1,632

1

08.11.2012, 16:27. Показов 11538. Ответов 10

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

привет.Подскажите

PHP
1
2
3
$xmlstr=simplexml_load_file(xml.xml);
$movies = new SimpleXMLElement($xmlstr);
echo $movies->movie[0]->plot;

выдает ошибку
Warning: simplexml_load_file() [function.simplexml-load-file]: I/O warning : failed to load external entity «xmlxml» in O:homelocalhostwwwindex.php on line 11

Fatal error: Uncaught exception ‘Exception’ with message ‘String could not be parsed as XML’ in O:homelocalhostwwwindex.php:12 Stack trace: #0 O:homelocalhostwwwindex.php(12): SimpleXMLElement->__construct(») #1 {main} thrown in O:homelocalhostwwwindex.php on line 12.

Может у меня не установлено расширение для использования ?



0



Programming

Эксперт

94731 / 64177 / 26122

Регистрация: 12.04.2006

Сообщений: 116,782

08.11.2012, 16:27

10

KOPOJI

Почетный модератор

Эксперт HTML/CSSЭксперт PHP

16842 / 6720 / 880

Регистрация: 12.06.2012

Сообщений: 19,967

08.11.2012, 16:32

2

Цитата
Сообщение от koza4ok
Посмотреть сообщение

PHP
1
$xmlstr=simplexml_load_file(xml.xml);

а вот так?

PHP
1
$xmlstr=simplexml_load_file('xml.xml');

Добавлено через 1 минуту
только зачем пытаться создать объект из объекта?



1



koza4ok

632 / 440 / 67

Регистрация: 19.09.2012

Сообщений: 1,632

08.11.2012, 18:13

 [ТС]

3

ой не то копирнул…..
Насчет

PHP
1
$xmlstr=simplexml_load_file('xml.xml');

помогли ».
Тебе спасибо.

Добавлено через 1 час 20 минут
Вопрос читал что Dom способ парсинга очень грузит систему.
Сейчас используют SAX или DOM?



0



21 / 21 / 2

Регистрация: 17.02.2011

Сообщений: 303

Записей в блоге: 1

19.05.2014, 16:45

4

проблемы с simplexml_load_file, есть файл на сайте в корне, пусть будет file.xml, после чего simplexml_load_file(‘file.xml’); работает корректно, всё выводит, если стоит загрузить это же файл или с другого сайта уже simplexml_load_file(‘http://example.com/file.xml’); не работает выдает:

warning: simplexml_load_file(http://example.com/file.xml): failed to open stream: HTTP request failed! HTTP/1.1 405 Not Allowed in /example.com/www/test.php on line 8.

warning: simplexml_load_file(): I/O warning : failed to load external entity «http://regionews.ua/asddf.xml» in /example.com/www/test.php on line 8.

но, вот пробую загрузить с сайта хотлайн пример их файла http://hotline.ua/download/hotline/hli.xml то работает всё ок, в чём может быть проблема?

Спасибо!



0



Почетный модератор

Эксперт HTML/CSSЭксперт PHP

16842 / 6720 / 880

Регистрация: 12.06.2012

Сообщений: 19,967

19.05.2014, 16:52

5

Цитата
Сообщение от Egoist0
Посмотреть сообщение

HTTP request failed! HTTP/1.1 405 Not Allowed

405 Not Allowed
З.Ы. грузите файл с помощью cURL



0



21 / 21 / 2

Регистрация: 17.02.2011

Сообщений: 303

Записей в блоге: 1

19.05.2014, 16:55

6

как его загрузить через cURL какой именно функцией это раз, два, почему тогда ссылка от хотлайна работает, а от моего сайта нет?



0



249 / 249 / 98

Регистрация: 26.07.2010

Сообщений: 1,685

19.05.2014, 16:56

7

использовал Dom, сам по себе не особо лаговый, но если парсить очень много случаются вылеты из-за нехватки памяти



0



KOPOJI

Почетный модератор

Эксперт HTML/CSSЭксперт PHP

16842 / 6720 / 880

Регистрация: 12.06.2012

Сообщений: 19,967

19.05.2014, 17:04

8

Цитата
Сообщение от Egoist0
Посмотреть сообщение

как его загрузить через cURL

PHP
1
2
3
4
5
6
$curl = curl_init('http://example.com/file.xml');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/34.0.1847.116 Chrome/34.0.1847.116 Safari/537.36');
file_put_contents('./file.xml', curl_exec($curl));
curl_close($curl);

Цитата
Сообщение от Egoist0
Посмотреть сообщение

почему

без понятия



0



21 / 21 / 2

Регистрация: 17.02.2011

Сообщений: 303

Записей в блоге: 1

19.05.2014, 17:14

9

и что даст это? как в итоге парсить?



0



Почетный модератор

Эксперт HTML/CSSЭксперт PHP

16842 / 6720 / 880

Регистрация: 12.06.2012

Сообщений: 19,967

19.05.2014, 17:19

10

Откуда же я знаю, что это даст? Ссылка на файл мне неизвестна, да и нет особого желания. Парсить — как обычно, с локального файла. Если, конечно, он скачается



0



21 / 21 / 2

Регистрация: 17.02.2011

Сообщений: 303

Записей в блоге: 1

19.05.2014, 17:28

11

понятно, значит это код который, позволяет скачать файл на локал, и открывать его потом уже локально у себя на сайте.



0



0 Пользователей и 1 Гость просматривают эту тему.

  • 19 Ответов
  • 7460 Просмотров

Здрасти!

С joomlaportal скачать Joomla 3.0.1.
На 4 шаге прогрессбар какое-то время дергается напротив строчки «Создание таблиц баз данных» и потом кидает меня на 3 шаг.

В php.ini я написал max_execution_time = 900, как это здесь рекомендовалось — не помогло.

Полез смотреть логи апача, там написано вот что:

[Mon Mar 04 15:57:25.880540 2013] [:error] [pid 2192:tid 1048] [client 127.0.0.1:5280] PHP Warning:  simplexml_load_file() [<a href=’function.simplexml-load-file’>function.simplexml-load-file</a>]: I/O warning : failed to load external entity &quot;file:///C:/Apache24/htdocs/templates/atomic/templateDetails.xml&quot; in C:\Apache24\htdocs\libraries\joomla\installer\installer.php on line 1891, referer: http://localhost/installation/index.php
[Mon Mar 04 15:57:25.880540 2013] [:error] [pid 2192:tid 1048] [client 127.0.0.1:5280] PHP Warning:  simplexml_load_file() [<a href=’function.simplexml-load-file’>function.simplexml-load-file</a>]: I/O warning : failed to load external entity &quot;file:///C:/Apache24/htdocs/templates/atomic/templateDetails.xml&quot; in C:\Apache24\htdocs\libraries\joomla\installer\installer.php on line 2100, referer: http://localhost/installation/index.php
[Mon Mar 04 15:57:27.797650 2013] [:error] [pid 2192:tid 1048] [client 127.0.0.1:5280] PHP Warning:  simplexml_load_file() [<a href=’function.simplexml-load-file’>function.simplexml-load-file</a>]: I/O warning : failed to load external entity &quot;file:///C:/Apache24/htdocs/administrator/manifests/packages/pkg_joomla.xml&quot; in C:\Apache24\htdocs\libraries\joomla\installer\installer.php on line 1891, referer: http://localhost/installation/index.php
[Mon Mar 04 15:57:27.797650 2013] [:error] [pid 2192:tid 1048] [client 127.0.0.1:5280] PHP Warning:  simplexml_load_file() [<a href=’function.simplexml-load-file’>function.simplexml-load-file</a>]: I/O warning : failed to load external entity &quot;file:///C:/Apache24/htdocs/administrator/manifests/packages/pkg_joomla.xml&quot; in C:\Apache24\htdocs\libraries\joomla\installer\installer.php on line 2100, referer: http://localhost/installation/index.php

По поводу XML в параметрах все нормально:

Подскажите, в чем дело?

« Последнее редактирование: 05.03.2013, 15:58:49 от b2z »

Записан

Зачем качать старую версию? Скачайте версию 3.0.3 с Joomla.org. В конце установки загрузите дополнительно русский языковой пакет.

Качал, устанавливал — та же проблема возникает

На этом же файле? /templates/atomic/templateDetails.xml

Да, ошибка та же и на том же файле.

Как оказалось, проблема не совсем не в Joomla.
Сравнил с 2.5.6 и 2.5.8 — там файлы
/templates/atomic/templateDetails.xml и administrator/manifests/packages/pkg_joomla.xml есть, в 3.0.1 и 3.0.3 их нет.
Раньше не допер проверить их наличие.
Спасибо.

Не до конца перенесли все файлы?

В архиве, который скачивал их нет…
Щас 2.5.8 (где они есть) установил, пока вроде нормально все.
Может в третьей они динамически создаются в процессе установки?

Так ведь в Joomla 3.0 не может быть этого файла /templates/atomic/templateDetails.xml, т.к. в дистрибутиве нет такого шаблона, как atomic
Есть только 2 шаблона beez3 и protostar

Но при установке (если кто не заметил, я ставлю на mssql, а не на mysql) она все равно пытается подцепить атомик.

Так ведь в Joomla 3.0 не может быть этого файла /templates/atomic/templateDetails.xml, т.к. в дистрибутиве нет такого шаблона, как atomic
Есть только 2 шаблона beez3 и protostar

Но при установке (если кто не заметил, я ставлю на mssql, а не на mysql) она все равно пытается подцепить атомик.

Это вообще странно. Хочется разобраться, что тут за чудеса.

Это вообще странно. Хочется разобраться, что тут за чудеса.

Щас попробовал 3.0.3 на MySQL поставить — все нормально встало, при установке на mssql обращается к атомику.

Щас попробовал 3.0.3 на MySQL поставить — все нормально встало, при установке на mssql обращается к атомику.

Весело!
На мой взгляд, все-таки рановато версию 3.0 рабочей объявили.

Я с mssql не работал… Да, все таки есть еще ошибки. Это бы в багтрекере оформить…

Я с mssql не работал… Да, все таки есть еще ошибки. Это бы в багтрекере оформить…

Эм…куда и что написать?

Тоже боролся с аналогичной ситуацией при установке Joomla 3.1.5- зависанием на 3-ем шаге установки

Параметры системы такие:

в логе апачи такое исключение
[Sat Aug 03 00:14:30.960889 2013] [:error] [pid 11600:tid 1144] [client ::1:7420] PHP RuntimeException:   SQL= in C:\_directprovider.ru\z3\libraries\joomla\database\driver\mysqli.php on line 576,

Закомментировал строчку 576 в librariesjoomladatabasedrivermysqli.php, успешно прошёл 3-ий шаг, после чего опять раскомментировал! вот такие дела… может кому то тоже поможет.

Понравилась статья? Поделить с друзьями:
  • Ошибка failed to launch game
  • Ошибка failed to launch exe
  • Ошибка failed to launch denuvo license generator
  • Ошибка failed to launch client
  • Ошибка failed to initialize как исправить