PROBLEMA
- función de PHP
simplexml_load_file
es tirar de error parser error : xmlParseEntityRef
analizar al intentar cargar el archivo XML desde una dirección URL.
Causa
- XML devuelto por la URL no es un XML válido. Contiene
&
valor en lugar de &
. Es muy posible que haya otros errores que no son obvios en este momento.
cosas fuera de nuestro control
- Idealmente, deben asegurarse de que un XML válido se introduce en función PHP
simplexml_load_file
, pero parece que no tenemos ninguna control sobre cómo se crea el XML
- Tampoco es posible forzar
simplexml_load_file
para procesar un archivo XML no válido . No nos deja muchas opciones distintas de que arreglan el archivo XML en sí.
SOLUCIÓN POSIBLE
Convertir XML no válido a XML válido. Se puede hacer usando PHP tidy extension
. Puede encontrar más instrucciones en http://php.net/manual/en/book.tidy.php
Una vez que esté seguro de que la extensión existe o está instalada, haga lo siguiente.
/**
* As per the question asked, the URL is loaded into a variable first,
* which we can assume to be $xml
*/
$xml = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<project orderno="6" campaign_name="International Relief & Development for under developed nations">
<invalid-data>Some other data containing & in it</invalid-data>
<unclosed-tag>
</project>
XML;
/**
* Whenever we use tidy it is best to pass some configuration options
* similar to $tidyConfig. In this particular case we are making sure that
* tidy understands that our input and output is XML.
*/
$tidyConfig = array (
'indent' => true,
'input-xml' => true,
'output-xml' => true,
'wrap' => 200
);
/**
* Now we can use tidy to parse the string and then repair it.
*/
$tidy = new tidy;
$tidy->parseString($xml, $tidyConfig, 'utf8');
$tidy->cleanRepair();
/**
* If we try to output the repaired XML string by echoing $tidy it should look like.
<?xml version="1.0" encoding="utf-8"?>
<project orderno="6" campaign_name="International Relief & Development for under developed nations">
<invalid-data>Some other data containing & in it</invalid-data>
<unclosed-tag></unclosed-tag>
</project>
* As you can see that & is now fixed in campaign_name attribute
* and also with-in invalid-data element. You can also see that the
* <unclosed-tag> which didn't had a close tag, has been fixed too.
*/
echo $tidy;
/**
* Now when we try to use simplexml_load_string to load the clean XML. When we
* try to print_r it should look something like below.
SimpleXMLElement Object
(
[@attributes] => Array
(
[orderno] => 6
[campaign_name] => International Relief & Development for under developed nations
)
[invalid-data] => Some other data containing & in it
[unclosed-tag] => SimpleXMLElement Object
(
)
)
*/
$simpleXmlElement = simplexml_load_string($tidy);
print_r($simpleXmlElement);
PRECAUCIÓN
El desarrollador debe tratar de comparar el código XML no válido con un XML válido (generada por ordenado), al ver que no hay efectos secundarios adversos después de usar ordenado. Tidy hace un muy buen trabajo al hacerlo correctamente, pero nunca está de más verlo visualmente y estar 100% seguro. En nuestro caso, debería ser tan simple como comparar $ xml con $ tidy.
El XML no es válido. Es posible que no puedas cargarlo en absoluto. Los errores se pueden suprimir agregando '@' delante de 'simplexml_load_file' o agregando un marcador, consulte la página de manual de' simplexml_load_file' para obtener más información y elimine su pregunta, es un duplicado. – hakre
Veo que mi respuesta está recibiendo bastante atención, si esa es realmente la solución: ¿puede marcarla como "respuesta correcta"? Gracias. – ricricucit