Home » Php » parse xml multiple sibling child node before specific xml sibling child node using php

parse xml multiple sibling child node before specific xml sibling child node using php

Posted by: admin June 30, 2018 Leave a comment

Questions:

Hello Stackoverflowrian!
im trying to parse multiple mathml(xml) child node before specific child node which is <mspace breakline="newline" into an array. here are my .xml file

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

thats mean i want to get like this

$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>;

currently my coding is

<?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;
}

which give me output

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 );

Thanks in advance

Answers: