使用php

时间:2018-05-24 07:09:39

标签: php arrays xml

Hello Stackoverflowrian你好! 我试图在特定的子节点<mspace breakline="newline"之前解析多个mathml(xml)子节点到一个数组。这是我的.xml文件

<math xmlns="http://www.w3.org/1998/Math/MathML">
<mn>2</mn><mi>x</mi><mo>+</mo><mn>2</mn><mo>=</mo><mn>3</mn>
<mspace linebreak="newline"/>
<mn>2</mn><mi>x</mi><mo>=</mo><mn>3</mn><mo>-</mo><mn>2</mn>
<mspace linebreak="newline"/>
<mn>2</mn><mi>x</mi><mo>=</mo><mn>1</mn>
<mspace linebreak="newline"/>
<mi>x</mi><mo>=</mo><mfrac><mn>1</mn><mn>2</mn></mfrac>

这意味着我希望得到这样的

$array(0)=<mn>2</mn><mi>x</mi><mo>+</mo><mn>2</mn><mo>=</mo><mn>3</mn>;
$array(1)=<mn>2</mn><mi>x</mi><mo>=</mo><mn>3</mn><mo>-</mo><mn>2</mn>;
$array(2)=<mn>2</mn><mi>x</mi><mo>=</mo><mn>1</mn>;
$array(3)=<mi>x</mi><mo>=</mo><mfrac><mn>1</mn><mn>2</mn></mfrac>;

目前我的编码是

<?php

$xml1 = new SimpleXMLElement(file_get_contents('answer.xml'));
$xml1 = $xml1->asXml();
$dom = new DOMDocument;
$dom->loadXML($xml1);
$maths = $dom->getElementsByTagName('mspace');
$length = 0;
foreach ($maths as $math) {
$length++;
}


$root = simplexml_load_string($xml1);
for($i = 0; $i <= $length; $i++){
    foreach($root as $child)
    {
    if ($maths){ 
        $arrXml[] = $child->asXml();
         // break;
        }

    // 
    }
 print_r(array_values($arrXml));    
    break;
}

给我输出

Array ( [0] => 2 [1] => x [2] => + [3] => 2 [4] => = [5] => 3 [6] => [7] => 2 [8] => x [9] => = [10] => 3 [11] => - [12] => 2 [13] => [14] => 2 [15] => x [16] => = [17] => 1 [18] => [19] => x [20] => = [21] => 12 );

提前致谢

1 个答案:

答案 0 :(得分:1)

执行此操作的一种方法是循环MDN并为没有package com.admin.Model; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; @Document(collection="SignUp") public class SignUp { @Id private int id; private String fullName; private String email; private String password; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getFullName() { return fullName; } public void setFullName(String fullName) { this.fullName = fullName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String toString() { return id+""+fullName+""+password; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } } 作为名称的所有项创建数组。

一旦名称等于mspace,创建一个新的空数组并将其添加到占位符数组mspace以获取所有这些结果。

循环后使用childrenarray_map为数组条目创建整个字符串。

$result

implode