第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

有沒有更簡潔的方法來實現(xiàn) NHS 數(shù)據(jù)從 XML 到 JSON 的轉(zhuǎn)換

有沒有更簡潔的方法來實現(xiàn) NHS 數(shù)據(jù)從 XML 到 JSON 的轉(zhuǎn)換

PHP
慕尼黑5688855 2021-12-03 14:35:10
我正在使用來自公共 NHS API 的位置和地址數(shù)據(jù),它以 XML 格式輸入,我已將其轉(zhuǎn)換為 JSON 以在我的 web 應(yīng)用程序中使用。我的代碼正在運行并產(chǎn)生所需的結(jié)果,但是我不禁對這段代碼中嵌套的 foreach 循環(huán)的數(shù)量感到畏縮。有沒有更干凈的方法來實現(xiàn)相同的結(jié)果,并且性能更高?我曾嘗試使用 simplexml_load_string 和許多變體,但它拒絕輸出/解析包含 s:organisationSummary 數(shù)據(jù)的嵌套元素的內(nèi)容。這是 PHP 類class XmlElement {    public $name;    public $attributes;    public $content;    public $children;}class GpService{    protected $apiKey;    public function __construct()    {        $this->apiKey = env('NHS_API_KEY');    }    public function xmlToObject($xml) {        $parser = xml_parser_create();        xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);        xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);        xml_parse_into_struct($parser, $xml, $tags);        xml_parser_free($parser);        $elements = array();  // the currently filling [child] XmlElement array        $stack = array();        foreach ($tags as $tag) {          $index = count($elements);          if ($tag['type'] == "complete" || $tag['type'] == "open") {            $elements[$index] = new XmlElement;            $elements[$index]->name = $tag['tag'];            $elements[$index]->attributes = (isset($tag['attributes']))?$tag['attributes']:null;            $elements[$index]->content = (isset($tag['value']))?$tag['value']:null;            if ($tag['type'] == "open") {  // push              $elements[$index]->children = array();              $stack[count($stack)] = &$elements;              $elements = &$elements[$index]->children;            }          }          if ($tag['type'] == "close") {  // pop            $elements = &$stack[count($stack) - 1];            unset($stack[count($stack) - 1]);          }        }        return $elements[0];  // the single top-level element    }    }}
查看完整描述

2 回答

?
繁花不似錦

TA貢獻1851條經(jīng)驗 獲得超4個贊

您可以使用 DOM 和 XPath 表達式。所有數(shù)據(jù)都在{https://api.nhs.uk/data/services}organisationSummary節(jié)點內(nèi)。


下面的示例注冊service命名空間的前綴https://api.nhs.uk/data/services(這就是s示例中的 解析為)。然后它{https://api.nhs.uk/data/services}organisationSummary使用//service:organisationSummary表達式獲取任何節(jié)點。


對于每個組織,它$item使用標(biāo)量值的表達式構(gòu)建一個變量。循環(huán)用于{https://api.nhs.uk/data/services}addressLine節(jié)點。


// create the DOM document and load the XML 

$document = new DOMDocument();

$document->loadXML($xml);

// create an Xpath instance for the document - register namespace

$xpath = new DOMXpath($document);

$xpath->registerNamespace('service', 'https://api.nhs.uk/data/services');

$json = [

  "success" => true,

  // force object for data - it will be an array otherwise

  "data" => new stdClass()

];


// iterate over all organisationSummary nodes

foreach ($xpath->evaluate('//service:organisationSummary') as $index => $organisation) {

  // fetch single values

  $item = [

    "name" => $xpath->evaluate('string(service:name)', $organisation),

    "odscode" => $xpath->evaluate('string(service:odsCode)', $organisation),

    "postcode" => $xpath->evaluate('string(service:address/service:postcode)', $organisation),

    "telephone" => $xpath->evaluate('string(service:contact/service:telephone)', $organisation),

    "longitude" => $xpath->evaluate('string(service:geographicCoordinates/service:longitude)', $organisation),

    "latitude" => $xpath->evaluate('string(service:geographicCoordinates/service:latitude)', $organisation),

    "distance" => $xpath->evaluate('string(service:Distance)', $organisation)

  ];

  // add the addressLine values

  foreach ($xpath->evaluate('service:address/service:addressLine', $organisation) as $lineIndex => $line) {

    $item['addressline'.$lineIndex] = $line->textContent;

  }

  // add the $item

  $json['data']->{$index} = $item;

}


echo json_encode($json, JSON_PRETTY_PRINT);

輸出:


{

    "success": true,

    "data": {

        "0": {

            "name": "Highfields Surgery (R Wadhwa)",

            "odscode": "C82116",

            "postcode": "LE2 0NN",

            "telephone": "01162543253",

            "longitude": "-1.11859357357025",

            "latitude": "52.6293983459473",

            "distance": "0.247038430918239",

            "addressline0": "25 Severn Street",

            "addressline1": "Leicester",

            "addressline2": "Leicestershire"

        },

        "1": {

            "name": "Dr R Kapur & Partners",

            "odscode": "C82659",

            "postcode": "LE2 0TA",

            "telephone": "01162951258",

            "longitude": "-1.11907768249512",

            "latitude": "52.6310386657715",

            "distance": "0.30219913005026",

            "addressline0": "St Peters Health Centre",

            "addressline1": "Sparkenhoe Street",

            "addressline2": "Leicester",

            "addressline3": "Leicestershire"

        },

        ...


查看完整回答
反對 回復(fù) 2021-12-03
?
冉冉說

TA貢獻1877條經(jīng)驗 獲得超1個贊

您需要使用適當(dāng)?shù)姆椒▉肀闅v XML 文檔,而不是查看每個元素并檢查其名稱。


您的兩個最佳選擇是 DOM 方法和 XPath。如果您使用過前端 JavaScript 代碼(例如document.getElementsByTagName或document.getElementById),您就會熟悉前者。后者具有更陡峭的學(xué)習(xí)曲線,但功能要強大得多。(XSLT 也是轉(zhuǎn)換 XML 的好選擇,但我對它不是很熟悉。)


不過,第一步是使用正確的 XML 庫。您使用的 XML 函數(shù)級別非常低。我建議改用 PHP 的DomDocument擴展。讓我們潛入吧!


<?php

$xml = file_get_contents("nhs.xml");

// assume XML document is stored in a variable called $xml

$dom = new DomDocument;

$dom->loadXml($xml);

// thankfully we can ignore namespaces!

$summaries = $dom->getElementsByTagName("organisationSummary");

// go through each <organisationSummary> element

foreach ($summaries as $os) {

    $entry_data = [

        // note we're using $os and not $dom now, so we get child elements of this particular element

        "name"         => $os->getElementsByTagName("name")[0]->textContent,

        "odscode"      => $os->getElementsByTagName("odsCode")[0]->textContent,

        "addressline0" => $os->getElementsByTagName("addressLine")[0]->textContent,

        // provide a default empty string in case there's no further lines

        "addressline1" => $os->getElementsByTagName("addressLine")[1]->textContent ?? "",

        "addressline2" => $os->getElementsByTagName("addressLine")[2]->textContent ?? "",

        "addressline3" => $os->getElementsByTagName("addressLine")[3]->textContent ?? "",

        "postcode"     => $os->getElementsByTagName("postcode")[0]->textContent,

        "telephone"    => $os->getElementsByTagName("telephone")[0]->textContent,

        "longitude"    => $os->getElementsByTagName("longitude")[0]->textContent,

        "latitude"     => $os->getElementsByTagName("latitude")[0]->textContent,

        "distance"     => $os->getElementsByTagName("Distance")[0]->textContent,

    ];

    $json_data[] = $entry_data;

}

if (count($json_data)) {

    $output = ["success" => true, "data" => $json_data];

} else {

    $output = ["success" => false];

}

echo json_encode($output, JSON_PRETTY_PRINT);


查看完整回答
反對 回復(fù) 2021-12-03
  • 2 回答
  • 0 關(guān)注
  • 192 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號