使用PHP将JSON数据转换为HTML下拉列表

How can I convert this XML/JSON data into an HTML select droplist using PHP?

JSON/XML Data:

{"CountryList":"<Countries><Country><Code>AF<\/Code><Name>Afghanistan<\/Name><\/Country><Country><Code>AL<\/Code><Name>Albania<\/Name><\/Country><Country><Code>DZ<\/Code><Name>Algeria<\/Name><\/Country><Country><Code>AS<\/Code><Name>American Samoa<\/Name><\/Country><Country><Code>AD<\/Code><Name>Andorra<\/Name><\/Country><Country><Code>AO<\/Code><Name>Angola<\/Name><\/Country><Country><Code>AI<\/Code><Name>Anguilla<\/Name><\/Country><Country><Code>AQ<\/Code><Name>Antarctica<\/Name><\/Country><Country><Code>AG<\/Code><Name>Antigua &amp; Barbuda<\/Name><\/Country><Country><Code>AR<\/Code><Name>Argentina<\/Name><\/Country><Country><Code>AM<\/Code><Name>Armenia<\/Name><\/Country><Country><Code>AW<\/Code><Name>Aruba<\/Name><\/Country><Country><Code>AU<\/Code><Name>Australia<\/Name><\/Country><Country><Code>AT<\/Code><Name>Austria<\/Name><\/Country><Country><Code>AZ<\/Code><Name>Azerbaijan<\/Name><\/Country><Country><Code>BS<\/Code><Name>Bahamas<\/Name><\/Country><Country><Code>BH<\/Code><Name>Bahrain<\/Name><\/Country><Country><Code>BD<\/Code><Name>Bangladesh<\/Name><\/Country><Country><Code>BB<\/Code><Name>Barbados<\/Name><\/Country><Country><Code>BY<\/Code><Name>Belarus (Belorussia)<\/Name><\/Country><\/Countries>","Error":{"ErrorCode":0,"ErrorMessage":""},"Status":1,"TokenId":"bdf0738c-7a47-410e-961a-52da9b5df935"}

Desired HTML output:

<select>
    <option value="AF|Afghanistan">Afghanistan</option>
    <option value="AL|Albania">Albania</option>
    <option value="DZ|Algeria">Algeria</option>
    <option value="AS|American Samoa">American Samoa</option>
    <option value="AD|Andorra">Andorra</option>
    <option value="AO|Angola">Angola</option>
    <option value="AI|Anguilla">Anguilla</option>
    <option value="AQ|Antarctica">Antarctica</option>
    <option value="AG|Antigua & Barbuda">Antigua & Barbuda</option>
    <option value="AR|Argentina">Argentina</option>
    <option value="AM|Armenia">Armenia</option>
    <option value="AW|Aruba">Aruba</option>
    <option value="AU|Australia">Australia</option>
    <option value="AT|Austria">Austria</option>
    <option value="AZ|Azerbaijan">Azerbaijan</option>
    <option value="BS|Bahamas">Bahamas</option>
    <option value="BH|Bahrain">Bahrain</option>
    <option value="BD|Bangladesh">Bangladesh</option>
    <option value="BB|Barbados">Barbados</option>
    <option value="BY|Belarus (Belorussia)">Belarus (Belorussia)</option
</select>


after parsing, am getting array like this

Array
(
        [CountryList] => AFAfghanistanALAlbaniaDZAlgeriaASAmerican SamoaADAndorraAOAngolaAIAnguillaAQAntarcticaAGAntigua & BarbudaARArgentinaAMArmeniaAWArubaAUAustraliaATAustriaAZAzerbaijanBSBahamasBHBahrainBDBangladeshBBBarbadosBYBelarus (Belorussia)

         [Error] => Array
                 (
                         [ErrorCode] => 0
                         [ErrorMessage] =>
                 )

         [Status] => 1

         [TokenId] => 5a5e32c4-77ee-4703-b0b1-4ff275ac61asw0 )


Data that i am getting see in the below link https://drive.google.com/file/d/0B9VV_J4sKTatdWJGeHJkOVZzZ00/view?usp=sharing

try this one may be it will helpfull for you.

Solution

$json = json_decode($data);$source = new DOMDocument();
$source->loadXml($json->CountryList);
$xpath = new DOMXpath($source);
$target = new DOMDocument();
$options = $target->appendChild($target->createElement('select'));

foreach ($xpath->evaluate('/Countries/Country') as $country) {
    $countryCode = $xpath->evaluate('string(Code)', $country);
    $countryName = $xpath->evaluate('string(Name)', $country);
    $option = $options->appendChild(
        $target->createElement('option')
    );
    $option->setAttribute('value', $countryCode . "|" . $countryName);
    $option->appendChild($target->createTextNode($countryName));
}

$target->formatOutput = TRUE;
echo $target->saveXml($options);

Output:

    <select>
        <option value="AF|Afghanistan">Afghanistan</option>
        <option value="AL|Albania">Albania</option>
        <option value="DZ|Algeria">Algeria</option>
        <option value="AS|American Samoa">American Samoa</option>
        <option value="AD|Andorra">Andorra</option>
        <option value="AO|Angola">Angola</option>
        <option value="AI|Anguilla">Anguilla</option>
        <option value="AQ|Antarctica">Antarctica</option>
        <option value="AG|Antigua & Barbuda">Antigua & Barbuda</option>
        <option value="AR|Argentina">Argentina</option>
        <option value="AM|Armenia">Armenia</option>
        <option value="AW|Aruba">Aruba</option>
        <option value="AU|Australia">Australia</option>
        <option value="AT|Austria">Austria</option>
        <option value="AZ|Azerbaijan">Azerbaijan</option>
        <option value="BS|Bahamas">Bahamas</option>
        <option value="BH|Bahrain">Bahrain</option>
        <option value="BD|Bangladesh">Bangladesh</option>
        <option value="BB|Barbados">Barbados</option>
        <option value="BY|Belarus (Belorussia)">Belarus (Belorussia)</option
     </select>

Your data is not XML, it is a JSON string.

If you can access to original XML data, you can obtain better results.

By the way, to decode your current data, use json_decode:

$data = json_decode($data);

Then, create a pattern that match the countries schema and match all the occurrences in the $data->CountryList

$pattern = '{([^<]+)</Code>([^<]+)</Name></Country>}';
preg_match_all( $pattern, $data->CountryList, $matches );

At this point, you can output your <option> list through a foreach loop:

foreach( $matches[0] as $key => $val )
{
    echo sprintf( '<option value="%s">%s</option>', $matches[1][$key], $matches[2][$key] );
}

eval.in demo

Edit: pattern syntax

{([^<]+)</Code>([^<]+)</Name></Country>}
 └──┬──┘└──┬──┘└──┬──┘└─┬─────────────┘
    │      │      │     └ 2nd and 3rd tags (not captured)
    │      │      └ One or more chars except ‘<’ (2nd captured group)
    │      └ 1st tag (not captured)
    └ One or more chars except ‘<’ (1st captured group)

You JSON contains the countries as an XML. So you have to decode the JSON first:

$json = json_decode($data);

Parse the XML after that:

$source = new DOMDocument();
$source->loadXml($json->CountryList);
$xpath = new DOMXpath($source);

You can use DOM to generate the target XML. Create a target document and append the root node. Iterate the countries using Xpath and create/append the option elements.

$target = new DOMDocument();
$options = $target->appendChild($target->createElement('select'));

foreach ($xpath->evaluate('/Countries/Country') as $country) {
  $option = $options->appendChild(
    $target->createElement('option')
  );
  $option->setAttribute(
    'value', 
    $xpath->evaluate('string(Code)', $country)
  );
  $option->appendChild(
    $target->createTextNode(
      $xpath->evaluate('string(Name)', $country)
    )
  );
}

$target->formatOutput = TRUE;
echo $target->saveXml($options);

Output:

<select>
  <option value="AF">Afghanistan</option>
  <option value="AL">Albania</option>
  <option value="DZ">Algeria</option>
  <option value="AS">American Samoa</option>
  <option value="AD">Andorra</option>
  <option value="AO">Angola</option>
  <option value="AI">Anguilla</option>
  ...