Zend_JSON: Кодировать все не так - зачем? - PullRequest
15 голосов
/ 16 ноября 2009

Мой Zend_Json запутался в кодировании объекта здесь. Я кодирую ассоциативный массив, который имеет два элемента: Элемент один - это другой ассоциативный массив, а элемент 2 - строка HTML. Он выдумывает так, что строковая часть HTML содержит только NULL !!?!?!?!?

Вот элемент UNencoded, когда я делаю var_dump на нем ... извините за элемент looong ... Это очень странно - я не понимаю, что здесь не так ...

array (
  'map' => 
  array (
    0 => 
    array (
      'id' => '1403',
      'name' => 'Amborovy Airport (Philibert Tsiranana Airport)',
      'label' => 'Amborovy Airport (Philibert Tsiranana Airport)',
      'html' => 'Amborovy Airport (Philibert Tsiranana Airport)',
      'lat' => '-0.666944',
      'lng' => '46.3517',
    ),
    1 => 
    array (
      'id' => '6160',
      'name' => 'Generalissimo Francisco de Miranda Airbase',
      'label' => 'Generalissimo Francisco de Miranda Airbase',
      'html' => 'Generalissimo Francisco de Miranda Airbase',
      'lat' => '0.485',
      'lng' => '-66.8436',
    ),
    2 => 
    array (
      'id' => '7808',
      'name' => 'Tirana International Airport',
      'label' => 'Tirana International Airport',
      'html' => 'Tirana International Airport',
      'lat' => '41.4150929722',
      'lng' => '19.7233001667',
    ),
    3 => 
    array (
      'id' => '20881',
      'name' => 'Tiranë Heliport',
      'label' => 'Tiranë Heliport',
      'html' => 'Tiranë Heliport',
      'lat' => 41.315865416667,
      'lng' => 19.888245972222,
    ),
    4 => 
    array (
      'id' => '5218',
      'name' => 'Abadan Airport',
      'label' => 'Abadan Airport',
      'html' => 'Abadan Airport',
      'lat' => '0.371111',
      'lng' => '48.2283',
    ),
    5 => 
    array (
      'id' => '5330',
      'name' => 'Lar Airport',
      'label' => 'Lar Airport',
      'html' => 'Lar Airport',
      'lat' => '0.673056',
      'lng' => '54.3814',
    ),
    6 => 
    array (
      'id' => '7808',
      'name' => 'Tirana International Airport',
      'label' => 'Tirana International Airport',
      'html' => 'Tirana International Airport',
      'lat' => '41.4150929722',
      'lng' => '19.7233001667',
    ),
    7 => 
    array (
      'id' => '20881',
      'name' => 'Tiranë Heliport',
      'label' => 'Tiranë Heliport',
      'html' => 'Tiranë Heliport',
      'lat' => 41.315865416667,
      'lng' => 19.888245972222,
    ),
    8 => 
    array (
      'id' => '5218',
      'name' => 'Abadan Airport',
      'label' => 'Abadan Airport',
      'html' => 'Abadan Airport',
      'lat' => '0.371111',
      'lng' => '48.2283',
    ),
    9 => 
    array (
      'id' => '5225',
      'name' => 'Ahvaz Airport',
      'label' => 'Ahvaz Airport',
      'html' => 'Ahvaz Airport',
      'lat' => '0.337431',
      'lng' => '48.762',
    ),
    10 => 
    array (
      'id' => '5242',
      'name' => 'Ardabil Airport',
      'label' => 'Ardabil Airport',
      'html' => 'Ardabil Airport',
      'lat' => '0.325556',
      'lng' => '48.4242',
    ),
    11 => 
    array (
      'id' => '5243',
      'name' => 'Asalouyeh Airport',
      'label' => 'Asalouyeh Airport',
      'html' => 'Asalouyeh Airport',
      'lat' => '0.481389',
      'lng' => '52.6153',
    ),
    12 => 
    array (
      'id' => '5251',
      'name' => 'Bandar Abbas International Airport',
      'label' => 'Bandar Abbas International Airport',
      'html' => 'Bandar Abbas International Airport',
      'lat' => '0.218056',
      'lng' => '56.3778',
    ),
    13 => 
    array (
      'id' => '5259',
      'name' => 'Birjand Airport',
      'label' => 'Birjand Airport',
      'html' => 'Birjand Airport',
      'lat' => '0.898056',
      'lng' => '59.2661',
    ),
    14 => 
    array (
      'id' => '5278',
      'name' => 'Dezful Airport',
      'label' => 'Dezful Airport',
      'html' => 'Dezful Airport',
      'lat' => '0.434444',
      'lng' => '48.3976',
    ),
    15 => 
    array (
      'id' => '5306',
      'name' => 'Jiroft Airport',
      'label' => 'Jiroft Airport',
      'html' => 'Jiroft Airport',
      'lat' => '0.726944',
      'lng' => '57.6703',
    ),
    16 => 
    array (
      'id' => '5326',
      'name' => 'Konarak Airport',
      'label' => 'Konarak Airport',
      'html' => 'Konarak Airport',
      'lat' => '0.443333',
      'lng' => '60.3819',
    ),
    17 => 
    array (
      'id' => '5330',
      'name' => 'Lar Airport',
      'label' => 'Lar Airport',
      'html' => 'Lar Airport',
      'lat' => '0.673056',
      'lng' => '54.3814',
    ),
    18 => 
    array (
      'id' => '5331',
      'name' => 'Lavan Airport',
      'label' => 'Lavan Airport',
      'html' => 'Lavan Airport',
      'lat' => '0.810278',
      'lng' => '53.3561',
    ),
    19 => 
    array (
      'id' => '5359',
      'name' => 'Parsabad-Moghan Airport',
      'label' => 'Parsabad-Moghan Airport',
      'html' => 'Parsabad-Moghan Airport',
      'lat' => '0.603606',
      'lng' => '47.8815',
    ),
    20 => 
    array (
      'id' => '5361',
      'name' => 'Persian Gulf Airport (Khalije Fars Airport)',
      'label' => 'Persian Gulf Airport (Khalije Fars Airport)',
      'html' => 'Persian Gulf Airport (Khalije Fars Airport)',
      'lat' => '0.379444',
      'lng' => '52.7375',
    ),
    21 => 
    array (
      'id' => '5393',
      'name' => 'Shahid Sadooghi Airport',
      'label' => 'Shahid Sadooghi Airport',
      'html' => 'Shahid Sadooghi Airport',
      'lat' => '0.905',
      'lng' => '54.2764',
    ),
    22 => 
    array (
      'id' => '5411',
      'name' => 'Tabriz International Airport',
      'label' => 'Tabriz International Airport',
      'html' => 'Tabriz International Airport',
      'lat' => '0.133889',
      'lng' => '46.235',
    ),
    23 => 
    array (
      'id' => '1416',
      'name' => 'Arrachart Airport',
      'label' => 'Arrachart Airport',
      'html' => 'Arrachart Airport',
      'lat' => '-0.349167',
      'lng' => '49.2917',
    ),
    24 => 
    array (
      'id' => '7808',
      'name' => 'Tirana International Airport',
      'label' => 'Tirana International Airport',
      'html' => 'Tirana International Airport',
      'lat' => '41.4150929722',
      'lng' => '19.7233001667',
    ),
    25 => 
    array (
      'id' => '20881',
      'name' => 'Tiranë Heliport',
      'label' => 'Tiranë Heliport',
      'html' => 'Tiranë Heliport',
      'lat' => 41.315865416667,
      'lng' => 19.888245972222,
    ),
  ),
  'html' => '<div><b>Search Results for terms \'Iran\'</b>  </div><a class="map-link"  href="javascript:void(0);" onclick="toggleMapsSearch(\'name\');">4 results of Names with "Iran"</a><div id="map-results-name" class="map-results-nubbin" style="display:none;"><a class="map-sub-links" href="javascript:mapClickHandler(\'1403\')">Amborovy Airport (Philibert Ts<span Style="color:red; Font-weight:bold;">Iran</span>ana Airport)</a><a class="map-sub-links" href="javascript:mapClickHandler(\'6160\')">Generalissimo Francisco De M<span Style="color:red; Font-weight:bold;">Iran</span>da Airbase</a><a class="map-sub-links" href="javascript:mapClickHandler(\'7808\')">T<span Style="color:red; Font-weight:bold;">Iran</span>a International Airport</a><a class="map-sub-links" href="javascript:mapClickHandler(\'20881\')">T<span Style="color:red; Font-weight:bold;">Iran</span>ë Heliport</a></div><a class="map-link" href="javascript:void(0);" onclick="toggleMapsSearch(\'city\');">4 results of Cities with "Iran"</a><div id="map-results-city" class="map-results-nubbin" style="display:none;"><a class="map-sub-links" href="javascript:mapClickHandler(\'5218\')">Abadan, <span Style="color:red; Font-weight:bold;">Iran</span> : Abadan Airport</a><a class="map-sub-links" href="javascript:mapClickHandler(\'5330\')">Lar, <span Style="color:red; Font-weight:bold;">Iran</span> : Lar Airport</a><a class="map-sub-links" href="javascript:mapClickHandler(\'7808\')">T<span Style="color:red; Font-weight:bold;">Iran</span>a : Tirana International Airport</a><a class="map-sub-links" href="javascript:mapClickHandler(\'20881\')">T<span Style="color:red; Font-weight:bold;">Iran</span>a : Tiranë Heliport</a></div><a class="map-link" href="javascript:void(0);" onclick="toggleMapsSearch(\'country\');">15 results of Countries with "Iran"</a><div id="map-results-country" class="map-results-nubbin" style="display:none;"><a class="map-sub-links" href="javascript:mapClickHandler(\'5218\')"><span Style="color:red; Font-weight:bold;">Iran</span> : Abadan Airport</a><a class="map-sub-links" href="javascript:mapClickHandler(\'5225\')"><span Style="color:red; Font-weight:bold;">Iran</span> : Ahvaz Airport</a><a class="map-sub-links" href="javascript:mapClickHandler(\'5242\')"><span Style="color:red; Font-weight:bold;">Iran</span> : Ardabil Airport</a><a class="map-sub-links" href="javascript:mapClickHandler(\'5243\')"><span Style="color:red; Font-weight:bold;">Iran</span> : Asalouyeh Airport</a><a class="map-sub-links" href="javascript:mapClickHandler(\'5251\')"><span Style="color:red; Font-weight:bold;">Iran</span> : Bandar Abbas International Airport</a><a class="map-sub-links" href="javascript:mapClickHandler(\'5259\')"><span Style="color:red; Font-weight:bold;">Iran</span> : Birjand Airport</a><a class="map-sub-links" href="javascript:mapClickHandler(\'5278\')"><span Style="color:red; Font-weight:bold;">Iran</span> : Dezful Airport</a><a class="map-sub-links" href="javascript:mapClickHandler(\'5306\')"><span Style="color:red; Font-weight:bold;">Iran</span> : Jiroft Airport</a><a class="map-sub-links" href="javascript:mapClickHandler(\'5326\')"><span Style="color:red; Font-weight:bold;">Iran</span> : Konarak Airport</a><a class="map-sub-links" href="javascript:mapClickHandler(\'5330\')"><span Style="color:red; Font-weight:bold;">Iran</span> : Lar Airport</a><a class="map-sub-links" href="javascript:mapClickHandler(\'5331\')"><span Style="color:red; Font-weight:bold;">Iran</span> : Lavan Airport</a><a class="map-sub-links" href="javascript:mapClickHandler(\'5359\')"><span Style="color:red; Font-weight:bold;">Iran</span> : Parsabad-Moghan Airport</a><a class="map-sub-links" href="javascript:mapClickHandler(\'5361\')"><span Style="color:red; Font-weight:bold;">Iran</span> : Persian Gulf Airport (Khalije Fars Airport)</a><a class="map-sub-links" href="javascript:mapClickHandler(\'5393\')"><span Style="color:red; Font-weight:bold;">Iran</span> : Shahid Sadooghi Airport</a><a class="map-sub-links" href="javascript:mapClickHandler(\'5411\')"><span Style="color:red; Font-weight:bold;">Iran</span> : Tabriz International Airport</a></div>',
)

А вот что происходит, когда я пытаюсь кодировать его в JSON с использованием класса Zends_JSON ...

{"map":[{"id":"1403","name":"Amborovy Airport (Philibert Tsiranana Airport)","label":"Amborovy Airport (Philibert Tsiranana Airport)","html":"Amborovy Airport (Philibert Tsiranana Airport)","lat":"-0.666944","lng":"46.3517"},{"id":"6160","name":"Generalissimo Francisco de Miranda Airbase","label":"Generalissimo Francisco de Miranda Airbase","html":"Generalissimo Francisco de Miranda Airbase","lat":"0.485","lng":"-66.8436"},{"id":"7808","name":"Tirana International Airport","label":"Tirana International Airport","html":"Tirana International Airport","lat":"41.4150929722","lng":"19.7233001667"},{"id":"20881","name":null,"label":null,"html":null,"lat":41.315865416667,"lng":19.888245972222},{"id":"5218","name":"Abadan Airport","label":"Abadan Airport","html":"Abadan Airport","lat":"0.371111","lng":"48.2283"},{"id":"5330","name":"Lar Airport","label":"Lar Airport","html":"Lar Airport","lat":"0.673056","lng":"54.3814"},{"id":"7808","name":"Tirana International Airport","label":"Tirana International Airport","html":"Tirana International Airport","lat":"41.4150929722","lng":"19.7233001667"},{"id":"20881","name":null,"label":null,"html":null,"lat":41.315865416667,"lng":19.888245972222},{"id":"5218","name":"Abadan Airport","label":"Abadan Airport","html":"Abadan Airport","lat":"0.371111","lng":"48.2283"},{"id":"5225","name":"Ahvaz Airport","label":"Ahvaz Airport","html":"Ahvaz Airport","lat":"0.337431","lng":"48.762"},{"id":"5242","name":"Ardabil Airport","label":"Ardabil Airport","html":"Ardabil Airport","lat":"0.325556","lng":"48.4242"},{"id":"5243","name":"Asalouyeh Airport","label":"Asalouyeh Airport","html":"Asalouyeh Airport","lat":"0.481389","lng":"52.6153"},{"id":"5251","name":"Bandar Abbas International Airport","label":"Bandar Abbas International Airport","html":"Bandar Abbas International Airport","lat":"0.218056","lng":"56.3778"},{"id":"5259","name":"Birjand Airport","label":"Birjand Airport","html":"Birjand Airport","lat":"0.898056","lng":"59.2661"},{"id":"5278","name":"Dezful Airport","label":"Dezful Airport","html":"Dezful Airport","lat":"0.434444","lng":"48.3976"},{"id":"5306","name":"Jiroft Airport","label":"Jiroft Airport","html":"Jiroft Airport","lat":"0.726944","lng":"57.6703"},{"id":"5326","name":"Konarak Airport","label":"Konarak Airport","html":"Konarak Airport","lat":"0.443333","lng":"60.3819"},{"id":"5330","name":"Lar Airport","label":"Lar Airport","html":"Lar Airport","lat":"0.673056","lng":"54.3814"},{"id":"5331","name":"Lavan Airport","label":"Lavan Airport","html":"Lavan Airport","lat":"0.810278","lng":"53.3561"},{"id":"5359","name":"Parsabad-Moghan Airport","label":"Parsabad-Moghan Airport","html":"Parsabad-Moghan Airport","lat":"0.603606","lng":"47.8815"},{"id":"5361","name":"Persian Gulf Airport (Khalije Fars Airport)","label":"Persian Gulf Airport (Khalije Fars Airport)","html":"Persian Gulf Airport (Khalije Fars Airport)","lat":"0.379444","lng":"52.7375"},{"id":"5393","name":"Shahid Sadooghi Airport","label":"Shahid Sadooghi Airport","html":"Shahid Sadooghi Airport","lat":"0.905","lng":"54.2764"},{"id":"5411","name":"Tabriz International Airport","label":"Tabriz International Airport","html":"Tabriz International Airport","lat":"0.133889","lng":"46.235"},{"id":"1416","name":"Arrachart Airport","label":"Arrachart Airport","html":"Arrachart Airport","lat":"-0.349167","lng":"49.2917"},{"id":"7808","name":"Tirana International Airport","label":"Tirana International Airport","html":"Tirana International Airport","lat":"41.4150929722","lng":"19.7233001667"},{"id":"20881","name":null,"label":null,"html":null,"lat":41.315865416667,"lng":19.888245972222}],"html":null}

Обратите внимание, в конце - огромный кусок HTML - GONE заменен на ноль .... что здесь происходит: (


EDIT

После некоторого расследования я обнаружил эту ошибку в своих журналах ошибок:

PHP Warning:  json_encode() [<a href='function.json-encode'>function.json-encode</a>]: Invalid UTF-8 sequence in argument in C:\wamp\www\fltdata\library\Zend\Json.php

Думаю, это как-то связано с проблемой, с которой я сталкиваюсь? Как мне это исправить?


EDIT

Моя версия Php - 5.2.9-2 - я сомневаюсь, что это связано с проблемой, которая была в версиях, предшествующих 5.2.7 ... помогите, пожалуйста, ребята !!!


EDIT

Запуск объекта через json_encode () возвращает тот же результат, и я получаю ту же ошибку:

PHP Warning:  json_encode() [<a href='function.json-encode'>function.json-encode</a>]: Invalid UTF-8 sequence in argument in...

Я в тупике: (


РЕШЕНИЕ

WOO HOOO !!!! Я понял это: я просто запускаю строковую переменную html через функцию utf8_encode, а затем запускаю на ней функцию кодирования JSON:

$ result ['html'] = utf8_encode ($ result ['html']);

И это работает - спасибо всем за помощь, ребята - я чувствую себя сильно ограниченным из-за того, что не могу голосовать более одного раза за каждый из постов здесь - вы все были фанатичной помощью: D Еще раз спасибо !!!

Ответы [ 3 ]

12 голосов
/ 16 ноября 2009

Вы исправили это, обновив версию PHP до версии, более поздней, чем версия 5.2.7.

В этой функции PHP json_encode до этой версии существовала серьезная ошибка UTF-8 . См. список изменений для получения более подробной информации.


Так как вы заметили, что вы используете PHP версии 5.2.9.2, ваша версия должна быть хорошей :) Пробовали ли вы перенаправлять определенное содержимое HTML через PHP json_encode () вручную?

Или, может быть, через utf8_encode () или utf8_decode () ?

2 голосов
/ 16 ноября 2009

Я вижу только одну возможную область, где NULL может быть возвращен из Encoder.php. Я бы начал отладку, выполнив несколько var_dumps внутри этой функции в Zend / Json / Encoder.php

protected function _encodeDatum(&$value)
{
    $result = 'null';

    if (is_int($value) || is_float($value)) {
        $result = (string) $value;
        $result = str_replace(",", ".", $result);
    } elseif (is_string($value)) {
        $result = $this->_encodeString($value);
    } elseif (is_bool($value)) {
        $result = $value ? 'true' : 'false';
    }

    return $result;
}

Я не совсем уверен, почему ваша HTML-строка не будет распознаваться как таковая, но я мог бы попытаться ввести ее перед кодированием.

array('html' => (string) $yourHtmlStr);
1 голос
/ 01 июня 2012

Обычно это происходит, если вы используете substr() или $somestring[0] в строке utf-8, которая содержит многобайтовые буквы. Используйте mb_ префиксные функции для редактирования данных такого типа, тогда у вас не будет проблем с json_encode()

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...