simplexml_load_string не конвертирует специальные символы с php

я пытаюсь преобразовать xml в json с запросом CURL, и специальные символы не декодируются должным образом.

Ниже мой код

function APIRequest($zip) {

   $URL = "http://www.example.com";

   $options = array(
       CURLOPT_RETURNTRANSFER => true,   // return web page
       CURLOPT_HEADER         => false,  // don't return headers
       CURLOPT_FOLLOWLOCATION => true,   // follow redirects
       CURLOPT_ENCODING       => "",     // handle compressed
       CURLOPT_USERAGENT      => "test", // name of client
       CURLOPT_AUTOREFERER    => true,   // set referrer on redirect
   );

   $ch = curl_init($URL);

   curl_setopt_array($ch, $options);

   $response = curl_exec($ch);
   curl_close($ch);

   $xml = simplexml_load_string(utf8_encode($response));
   $json = json_encode($xml);
   $json_response = json_decode($result);
   return $json_response;
}

person Sree    schedule 12.03.2019    source источник
comment
И что? Мы должны угадать вход и выход?   -  person u_mulder    schedule 12.03.2019
comment
Какая кодировка в исходниках? Какую кодировку вы используете при печати JSON? Проверьте также этот ответ: stackoverflow.com/a/6607228/1346234   -  person Justinas    schedule 12.03.2019
comment
Возможный дубликат строк json_encode(), отличных от utf-8?   -  person Justinas    schedule 12.03.2019


Ответы (1)


Попробуйте следующий код (вы можете заменить file_get_contents() функцией с cURL).

<?php
header('Content-type: text/html; charset=utf-8');

// converts XML content to JSON
// receives the URL address of the XML file. Returns a string with the JSON object
function XMLtoJSON($xml) {
  $xml_cnt = file_get_contents($xml);    // gets XML content from file
  $xml_cnt = str_replace(array("\n", "\r", "\t"), '', $xml_cnt);    // removes newlines, returns and tabs

  // replace double quotes with single quotes, to ensure the simple XML function can parse the XML
  $xml_cnt = trim(str_replace('"', "'", $xml_cnt));
  $simpleXml = simplexml_load_string($xml_cnt);

  return json_encode($simpleXml);    // returns a string with JSON object
}

echo XMLtoJSON('test1.xml');
person CoursesWeb    schedule 12.03.2019