Click here to Skip to main content
15,888,325 members
Please Sign up or sign in to vote.
3.00/5 (2 votes)
See more:
Many sorry for posting such a basic question, but honestly I found a lot about reading, but not much about specific writing.

I have a xml file that looks like this:

XML
<?xml version="1.0" encoding="ISO-8859-1"?>
<tabuleiro>
    <linha> <!-- Linha inicial -->
        <coluna1>3</coluna1>
        <coluna2>3</coluna2>
        <coluna3>3</coluna3>
        <coluna4>3</coluna4>
        <coluna5>3</coluna5>
        <coluna6>3</coluna6>
        <coluna7>3</coluna7>

    </linha>
    <linha> <!-- primeira linha do tabuleiro -->
        <coluna1>0</coluna1>
        <coluna2>0</coluna2>
        <coluna3>0</coluna3>
        <coluna4>0</coluna4>
        <coluna5>0</coluna5>
        <coluna6>0</coluna6>
        <coluna7>0</coluna7>
    </linha>
<linha>
        <coluna1>0</coluna1>
        <coluna2>0</coluna2>
        <coluna3>0</coluna3>
        <coluna4>0</coluna4>
        <coluna5>0</coluna5>
        <coluna6>0</coluna6>
        <coluna7>0</coluna7>
    </linha>
<linha>



...............


Let's say I want to update the coluna2 element from the second 'linha'. I believe it's something like this:

PHP
$doc = new DOMDocument();
$doc->load('tabuleiro.xml');
$cols = $path->query("linha");
    foreach($cols as $col)
        {
        if ...

        }
    $dom->save('tabuleiro.xml');



But I dont know what to put on that if clause (already tried some options but none of them working).

Can you help me ?
Posted
Updated 6-Mar-11 13:17pm
v2

1 solution

It is very simple for your XML file. Convert the XML to a simple hierarchial object. Set the values and save it back as XML.

PHP
$sxe = new SimpleXMLElement('test.xml', NULL, TRUE);
$linha=$sxe->linha;
$linha[2]->coluna2=30;
file_put_contents('test.xml', $sxe->asXML());


Where $linha[2] refer to second linha
 
Share this answer
 
Comments
Maxdd 7 7-Mar-11 10:19am    
Excelent answer! Thank you very much.

Just for curious, how could use the same using DOM ?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900