php 使用fast-xml-parser对xml进行React-Native解析

gab6jxml  于 2022-12-02  发布在  PHP
关注(0)|答案(1)|浏览(277)

我收到此错误
[未处理的承诺拒绝:类型错误:(0,_fastXmlParser.parse)不是函数。(在“(0,_fastXmlParser.parse)(数据)”中,“(0,_fastXmlParser.parse)"未定义)]
当使用fast-xml-parser包时,我尝试解析此XML并将其记录在控制台中,这是目前为止的代码:-

import { parse } from 'fast-xml-parser';

function test(){
  const emp_number = 20209;
  fetch('http://website.com/partner/api.php?emp_number='+`${emp_number}`, {
  method: 'POST',
  headers: {
    Accept: 'text/plain',
    'Content-Type': 'text/plain'
  }
})
  .then((response) => response.text())
  .then((data) => {
            let obj = parse(data);
            let servicenumber = obj.counter.serviceNumber;
            let consumpationtype = obj.counter.consumpationtype;
            let currentread = obj.counter.currentread;
            let currentdate = obj.counter.currentdate;
            let lastread = obj.counter.lastread;
            let lastdate = obj.counter.lastdate;
            let consumpation = obj.counter.consumpation;
            console.log("CurrentReading:"+`${currentread}`);
});}

这是api.php

<?php
    header('Content-Type: text/plain');
    $gecolEmployee = $_GET['emp_number'];

    $serverName = "host\SqlS"; 
    $connectionInfo = array( "Database"=>"gecol");
    $conn = sqlsrv_connect( $serverName, $connectionInfo);
        $query = "SELECT * FROM readers WHERE emp_number=?";
        $result = sqlsrv_query($conn, $query, array($gecolEmployee));
        $row = sqlsrv_fetch_array($result);
        if( $conn ) {
            echo $row['xml'];
        }else{
            echo "خطأ.<br />";
            die( print_r( sqlsrv_errors(), true));
        }
?>

并且XML响应

<counter>
    <serviceNumber>200135644</serviceNumber>
    <consumpationtype>1</consumpationtype>
    <currentread>95808</currentread>
    <currentdate>29/6/2022</currentdate>
    <lastread>85808</lastread>
    <lastdate>29/5/2022</lastdate>
    <consumpation>?</consumpation>
    <counternumber>7038842</counternumber>
    <phonenumber>0928065968</phonenumber>
</counter>
qyswt5oh

qyswt5oh1#

我在使用最新版本的fast-xml-parser时遇到了同样的问题。我发现旧版本的fast-xml-parser工作得很好。

  • 卸载当前版本:npm卸载快速xml解析器
  • 安装此版本:npm i快速XML解析器@3.12.13

然后,导入该方法并使用它,它为我工作以下步骤:
从“fast-xml-parser”导入{parse}
常量资源示例XML = YOUR XML DATA
const parsedData =解析(resExampleXML)
控制台.warn(已解析数据)

相关问题