Annaccond
Annaccond

Reputation: 11

Parsing XML file to array in PHP

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>

I'm trying to get array of "text" elements like:

> Array (
>     [0] => text content
>     [1] => text content
>     [2] => text content
>     [3] => text content )

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

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.

Upvotes: 0

Views: 3950

Answers (3)

The fourth bird
The fourth bird

Reputation: 163217

A possible solution would be to use simplexml_load_string.

That will return an object of class SimpleXMLElement. Then you can use its properties to get the xml data.

To get the text from the text elements into your $values array you can use a foreach loop:

$xmlstring = file_get_contents("xmlfile.php?ID=someId");
$xml = simplexml_load_string($xmlstring);

$values = array();

foreach ($xml->g->text as $text) {
    $values[] = $text->__toString();
}

The $text variable in the foreach loop is of type SimpleXMLElement and you can use its __toString() method to get the text content.

Upvotes: 1

Rainner
Rainner

Reputation: 589

There's a trick you can do using json_encode/decode to convert and XML object into an array, try this:

$temp = simplexml_load_string( trim( $xmlstring ), "SimpleXMLElement", LIBXML_NOCDATA );
$data = json_decode( json_encode( $temp ), true );
print_r( $data );

The data you're looking for would be located in:

$data['g']['text']

Upvotes: 1

Vipin Singh
Vipin Singh

Reputation: 543

Use following function

$source_xml = simplexml_load_file($xmlUrl);

and use it in foreach loop

Upvotes: 0

Related Questions