簡體   English   中英

將XML行解析為json字符串

[英]Parse XML rows to json string

我需要在不同行的兩個XML標記之間獲取值。 XML文件是多級的。 例如,我需要<student></student>之間的每個數據,這些數據都放在數據庫的JSON字符串中:

<SchoolRoster>
   <Student>
      <name>John</name>
      <age>14</age>
      <course>
         <math>A</math>
         <english>B</english>
      </course>
      <course>
         <government>A+</government>
      </course>
   </Student>
   <Student>
      <name>Tom</name>
      <age>13</age>
      <course>
         <gym>A</gym>
         <geography>incomplete</geography>
      </course>
   </Student>
</SchoolRoster>

我嘗試了以下方法:

$entities = new SimpleXMLElement($xml);

preg_match_all('/<Student>(.*?)<\/Student>/s', $entities, $json);

$obj =  json_encode($json);

這只會返回

[]

有什么想法嗎? 它應該返回一個JSON字符串。

我希望我解釋得足夠清楚。 真正的初學者在這里:)

您不能對SimpleXMLElement對象運行preg_match_all

使用foreach循環遍歷所有學生,並創建一個簡單的數組,然后將其編碼為JSON字符串。

$xml = new SimpleXMLElement($yourXmlStr);

$studentsArr = array();

foreach($xml->student as $student) {
   // Dump student data in temp array
}

echo json_encode($studentsArr);

實際上,當我運行您的示例時,它給了我:

[[],[]]

但是,正如已經回答的那樣,您不能在SimpleXMLElement上運行preg_match_all ,至少不能以有用的方式運行。 相反,這要容易得多,因為在您的情況下SimpleXMLElement附帶了一個表達式匹配器

$entities = new SimpleXMLElement($xml);

$json = $entities->xpath('//Student');

$obj = json_encode($json);

它稱為xpath,是XML的查詢/表達式語言。 正則表達式適用於常規字符串,而不適用於XML。

另外,您還可以在您的情況下使用iterator_to_array

$entities = new SimpleXMLElement($xml);

$json = iterator_to_array($entities->Student, false);

$obj = json_encode($json);

這兩個示例將產生相同的結果,這將給您(印刷精美):

[
    {
        "name": "John",
        "age": "14",
        "course": [
            {
                "math": "A",
                "english": "B"
            },
            {
                "government": "A+"
            }
        ]
    },
    {
        "name": "Tom",
        "age": "13",
        "course": {
            "gym": "A",
            "geography": "incomplete"
        }
    }
]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM