I have a problem parsing external XML files to PHP array. Structure of XML file is like that: <?xml version="1.0" encoding="UTF-8" standalone="no"?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN" "http://www.w3.org/TR/SVG/DTD/svg10.dtd"> <svg style="shape-rendering:geometricPrecision;" xml:space="preserve" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMidYMid meet" viewBox="0 0 530 900" x="0px" y="0px" width="530px" height="900px"> <g font-family="'sans-serif"> <text x="0" y="76" font-size="14">text content</text> <text x="0" y="76" font-size="14">text content</text> <text x="0" y="76" font-size="14">text content</text> <text x="0" y="76" font-size="14">text content</text> <rect width="530" height="900" x="0" y="0" fill="white" fill-opacity="0" /></g></svg> Code (markup): I'm trying to get array of "text" elements like: Array ( [0] => text content [1] => text content [2] => text content [3] => text content ) PHP: I've tried few different ways but of some reason I have a problem to access to elements I want. The only working solution I found was: $xmlstring = file_get_contents("xmlfile.php?ID=someId"); $xml = new simpleXml2Array( $xmlstring, null ); $xmlarray = $xml->arr[g][0][content][text]; $values = array(); for( $i= 0 ; $i < count($xmlarray) ; $i++ ) { $values[] = $xmlarray[$i][content]; } print_r( $values ); Code (markup): It's using "simpleXml2Array" class but I'd like to avoid it and get values I want using foreach loop. I'm looking for the most simple and easy solution.
@hdewantara has it right, domdocument would be WAY better suited to this. I've never even seen that simplexml2array nonsense -- doesn't look good. That way you'd have a DOM, so use it: $doc = new DOMDocument(); $doc->load('xmlfile.php?ID=someId'); $textElements = $doc->getElementsByTagName('text'); $values = []; foreach ($textElements as $text) $values[] = $text->textContent; echo '<pre>', print_r($values), '</pre>'; Code (markup): Though depending on what you wanted to do with those texts, I may or may not copy them to that array since, well... the nodeList returned by getElementsByTagName is traversable so... Basically once you have a domdocument, you can access it's DOM just like you were in JavaScript.