1

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

5
  • 1
    Your data is not XML, is JSON with some tags (custom? I don't know the format) in the 'CountryList' object Commented Feb 24, 2016 at 12:53
  • from where come the data? From XML? You can't access to real XML? Commented Feb 24, 2016 at 12:56
  • At first glimpse the format looks broken. As if all the opening tags are missing in CountryList. Commented Feb 24, 2016 at 13:01
  • 1
    I'm voting to close this question as off-topic because it is - in its current form - a "please write my code" question Commented Feb 24, 2016 at 13:24
  • kindly see i have edited JSON/XML Data: in the post, Commented Feb 24, 2016 at 14:28

3 Answers 3

2

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>([^<]+)</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]);
}

3v4l.org 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)
Sign up to request clarification or add additional context in comments.

3 Comments

Won't it capture "Code>1" and "Name>Something" instead of "1" and "Something?"
@SparK No. See the demo (note also the rigid string structure and the kind of data, country-code, country-name)
@SparK it's not XML!
0

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>

Comments

0

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>
  ...

2 Comments

it's not working it is saying. Notice: Trying to get property of non-object in. Warning: DOMDocument::loadXML(): Empty string supplied as input in
sir need little bit help kindly see again question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.