I am using the following function to convert XML to Json:
function XMLtoJSON($xml) {
$xml = file_get_contents($xml); // gets XML content from file
$xml = str_replace(array("\n", "\r", "\t"), '', $xml); // removes newlines, returns and tabs
// replace double quotes with single quotes, to ensure the simple XML function can parse the XML
$xml = trim(str_replace('"', "'", $xml));
$simpleXml = simplexml_load_string($xml);
return stripslashes(json_encode($simpleXml)); // returns a string with JSON object
}
I am trying to convert the following XML file:
https://www.comdinheiro.com.br/temp/COMDINHEIRO_GabrielVilella1146066400.xml
So my code is:
$myVar1 = XMLtoJSON("https://www.comdinheiro.com.br/temp/COMDINHEIRO_GabrielVilella1146066400.xml");
var_dump($myVar1);
Here is the var_dump result:
string(455) "{"controle":{"data_hora":"2017-05-12 20:26:47","usuario":"GabrielVilella","ferramenta":"ExtratoCarteira016"},"variaveis":{"nome_portfolio":"ApelidoTodos","data_ini":"2015-05-05","data_fim":"2016-08-12","cas_dec_q":"2","cas_dec_v":"2","discrimina_fundos":"0","discrimina_fundos_cvm":"0","discrimina_ativos":"1","discrimina_cadgeral":"0","data_fim_agenda":"2017-06-05","filtro_eventos":"todos","filtro_tipo_ativo":"todos","flag_export":"xml"},"resposta":{}}"
The conversion works properly. However it fails to fill the elements of "resposta":{}. No error message is shown. So I ask: Why "resposta":{} is empty?
Related
I am trying to convert an xml feed to json, but using this code it fails to do anything. Any ideas?
<?php
$xml_string = 'https://xml.betfred.com/Horse-Racing-Daily.xml';
//read the XML file
$xml = file_get_contents($xml_string);
//encode the formatted data
$json = json_encode();
//generate the JSON file
header('Content-Type: application/json');
echo $json;
?>
You forgot to put $xml in the json_encode() method as parameter. Adjust your code like this:
$json = json_encode($xml);
this will however only convert the $xml string to json and that is probably not what you want.
To get close to what you are trying to do you could do:
$simpleXml = simplexml_load_string($xml);
$json = json_encode($simpleXml);
Your json might contain alot of junk, but maybe it will be enough for your needs.
I have been working several times with php and XML but this kind of XML has Html tags in the beginning and in the end:
Link To XML
there is no direct link to the xml file so I have to use file_get_contents().
Im using this php code:
$url = "https://www.tandildiario.com/suscripcion.php?section=4";
$xml = file_get_contents($url);
$feed = simplexml_load_string($xml);
foreach ($feed->channel->item as $item) {
.....
I try different thing ..most of the errors are like this:
Warning: simplexml_load_string(): Entity: line 14: parser error : Entity 'oacute' not defined in D:\reader.php on line 37
Since the original XML is incorrect (it contains unescaped HTML in the description-tags), you can fix it before trying to parse it. Add the CDATA-attributes yourself:
$url = "https://www.tandildiario.com/suscripcion.php?section=4";
$xml = file_get_contents($url);
// Add the CDATA tags for the description
$xml = str_replace('<description>', '<description><![CDATA[', $xml);
$xml = str_replace('</description>', ']]></description>', $xml);
$feed = simplexml_load_string($xml);
You could decode the HTML entities prior to loading the XML.
$url = "https://www.tandildiario.com/suscripcion.php?section=5";
$xml = file_get_contents($url);
$feed = simplexml_load_string(html_entity_decode($xml, null, "UTF-8"));
foreach ( $feed->channel->item as $item ) {
echo $item->asXML();
}
Say I have the following php:
$Url = sprintf( "http://www.wowhead.com/item=%u?xml", $EntryId );
$Xml = file_get_contents( $Url );
//echo htmlentities($Xml, ENT_COMPAT, 'UTF-8');
$Xml = simplexml_load_string( $Xml);
and lets say this is the xml:
http://www.wowhead.com/item=31065?xml
I know if T want say DisplayID I can do:
$DisplayId = $Xml->item->icon["displayId"];
However I want to get the values within the <json> part of the file.
<json>
<![CDATA[
"armor":464,"classs":4,"displayid":117596,"id":31064,"level":146,"name":"3Hood of Absolution","reqclass":16,"reqlevel":70,"slot":1,"slotbak":1,"source":[5],"sourcemore": [{"n":"Tydormu","t":1,"ti":23381}],"specs":[258],"subclass":1
]]>
</json>
I want to get the slotbak value, but I'm unsure how to do it. I did echo htmlentities($Xml, ENT_COMPAT, 'UTF-8'); to ensure I'm getting the xml file fine, and I am. But when I use json_decode or json_encode it tends to just either return { } { } { } or simply the object and not the value.
Does anyone know how I can do this?
You need to remove the <![CDATA[ and ]]> for json_decode to work.
Try this:
$json = $Xml->item->json;
$cleanedJson = str_ireplace(array('<![CDATA[', ']]>'), array('{', '}'), $json);
$jsonObject = json_decode($cleanedJson);
I've got an xml to parse with php, that contains some umlaut characters.
Every node that contains a string has the string wrapped in a cdata tag, but my problem starts before parsing the xml: when I load the file (I've also tried to print out the contents of the file with file_get_contests, same result), the umlaut characters get broken, so for example ü becomes ü. Running a htmlentities() is futile, as the characters are already broken at that point. The xml encode is utf-8, so I don't know what else to do to avoid this problem. Anyone can help me?
Edit:
xml sample 'locations.xml':
<?xml version="1.0" encoding="utf-8"?>
<locations>
<location>
<id>481</id>
<city><![CDATA[Zürich]]></city>
</location>
</locations>
php code:
function parseLocations(){
$xml = new DOMDocument();
$xml->load('locations.xml');
$xml->preserveWhiteSpace = false;
$data = array();
$locations = $xml->childNodes->item(0);
for($i=0; $i<$locations->childNodes->length; $i++){
$location = $locations->childNodes->item($i);
if($location->nodeName=="location"){
$tmp = parseVenue($location);
$data[] = $tmp;
}
}
echo var_export($data, true);
}
function parseVenue($location){
//I need to exclude some of the nodes
$exclude = array('#text');
$data = array();
for($i=0; $i<$location->childNodes->length; $i++){
$tag = $location->childNodes->item($i);
if(!in_array($tag->nodeName, $exclude)){
$data[$tag->nodeName] = $tag->nodeValue;
}
}
return $data;
}
echoed output:
array ( 0 => array ( 'id' => '481', 'city' => 'Zürich'), )
I parse an xml file with this code:
$file = file_get_contents('test.xml');
$xml = $file;
echo '<pre>';
$xml = htmlentities_decode ($xml);
print_r (simplexml_load_string($xml));
function htmlentities_decode( $string ){
$trans = get_html_translation_table(HTML_ENTITIES, ENT_QUOTES);
$trans = array_flip($trans);
return strtr($string, $trans);
}
My xml File has Umlauts like this decoded: &amul; or ß.
How do I have to decode/encode my output, that I have to decode/encode them, that they are shown in the same way like above? ( &amul; or ß).
Simple xml can not read them directly, so I have to decode them first, that simple xml can work with it.
Afterwards (after the pasring) I want to save the as utf8 to the database.
What is the best way, to do that?