Domanda

I have this file, I cant figure out how to parse this file.

type = 10
version = 1.2
PART
{
    part = foobie
    partName = foobie
    EVENTS
    {
        MakeReference
        {
            active = True
        }
    }
    ACTIONS
    {
    }
}
PART
{
    part = bazer
    partName = bazer
}

I want this to be a array which should look like

$array = array(
    'type' => 10,
    'version' => 1.2,
    'PART' => array(
        'part' => 'foobie',
        'partName' => 'foobie,
        'EVENTS' => array(
            'MakeReference' => array(
                'active' => 'True'
            )
        ),
        'ACTIONS' => array(
        )
    ),
    'PART' => array(
        'part' => 'bazer',
        'partName' => 'bazer'
    )
);

I tried with preg_match but that was not a success. Any ideas?

È stato utile?

Soluzione 2

Here is my approach.

First of all change Im changing the { to the line before. Thats pretty easy

$lines = explode("\r\n", $this->file);
foreach ($lines as $num => $line) {
    if (preg_match('/\{/', $line) === 1) {
       $lines[$num - 1] .= ' {';
       unset($lines[$num]);
    }
}

Now the input looks like this

PART {
    part = foobie

Now we can make the whole thing to XML instead, I know that I said a PHP array in the question, but a XML object is still fine enough.

foreach ($lines as $line) {
            if (preg_match('/(.*?)\{$/', $line, $matches)) {
                $xml->addElement(trim($matches[1]));
                continue;
            }

            if (preg_match('/\}/', $line)) {
                $xml->endElement();
                continue;
            }

            if (strpos($line, ' = ') !== false) {
                list($key, $value) = explode(' = ', $line);
                $xml->addElementAndContent(trim($key), trim($value));
            }
}

The addElement, actually just adds a to a string endElement adds a and addElementAndContent doing both and also add content between them.

And just for making the whole content being a XML object, im using

$xml = simplexml_load_string($xml->getXMLasText());

And now $xml is a XML object, which is so much easier to work with :)

Altri suggerimenti

Why not use a format that PHP can decode natively, like JSON?

http://php.net/json_decode

$json = file_get_contents("filename.txt");
$array = json_decode($json);
print_r($array);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top