PHP: Read existing xml file and write new content - php

I have a .xsd-file and of course I can create a .xml-file from it. So basically I have a blank .xml-file (with no data/text)
With PHP I want to read the blank .xml-file, interate the nodes and fill them depending on the tag with data from the database.
There seem to be many options: XMLReader, XMLWriter, DOMDocument, SimpleXML
I don't know where to start. What would be the easies/leanest way?
More Information:
Here you kann find the .xsd-file...
The following .xml-file I created:
<?xml version="1.0" encoding="utf-8"?><Patienten>
<InfoXML>
<DatumXML></DatumXML>
<NameTudokusys></NameTudokusys>
<VersionTudokusys></VersionTudokusys>
</InfoXML>
<Patient>
<Stammdaten>
<PatientID></PatientID>
<GeburtsJahr></GeburtsJahr>
<GeburtsMonat></GeburtsMonat>
<GeburtsTag></GeburtsTag>
<Geschlecht></Geschlecht>
<EinwilligungTumordoku></EinwilligungTumordoku>
<EinwilligungExterneStelle></EinwilligungExterneStelle>
</Stammdaten>
<Fall>
<Anamnese>
<RelevanteKrebsvorerkrankungen></RelevanteKrebsvorerkrankungen>
<JahrRelevanteKrebsvorerkrankungen></JahrRelevanteKrebsvorerkrankungen>
<NichtRelevanteKrebsvorerkrankungen></NichtRelevanteKrebsvorerkrankungen>
<JahrNichtRelevanteKrebsvorerkrankungen></JahrNichtRelevanteKrebsvorerkrankungen>
<DKGPatientenfragebogen></DKGPatientenfragebogen>
<PositiveFamilienanamnese></PositiveFamilienanamnese>
</Anamnese>
<Grundgesamtheiten></Grundgesamtheiten>
<Fallinfos>
<Zentrumsfall></Zentrumsfall>
<Organ></Organ>
<RegNr></RegNr>
<HauptNebenStandort></HauptNebenStandort>
<FallNummer></FallNummer>
<EingabeFalldaten></EingabeFalldaten>
</Fallinfos>
<Diagnose>
<DatumErstdiagnosePrimaertumor></DatumErstdiagnosePrimaertumor>
<DatumHistologischeSicherung></DatumHistologischeSicherung>
<ICDOHistologieDiagnose></ICDOHistologieDiagnose>
<Tumorauspraegung></Tumorauspraegung>
<ICDOLokalisation></ICDOLokalisation>
<KolonRektum></KolonRektum>
<TumorlokalisationRektum></TumorlokalisationRektum>
<praeT></praeT>
<praeN></praeN>
<praeM></praeM>
<UICCStadium></UICCStadium>
<SynchroneBehandlungKolorektalerPrimaertumoren></SynchroneBehandlungKolorektalerPrimaertumoren>
<MRTBecken></MRTBecken>
<CTBecken></CTBecken>
<AbstandFaszie></AbstandFaszie>
</Diagnose>
<PraetherapeutischeTumorkonferenz>
<VorstellungPraetherapeutischeTumorkonferenz></VorstellungPraetherapeutischeTumorkonferenz>
<EmpfehlungPraetherapeutischeTumorkonferenz></EmpfehlungPraetherapeutischeTumorkonferenz>
</PraetherapeutischeTumorkonferenz>
<EndoskopischePrimaertherapie>
<DatumTherapeutischeKoloskopie></DatumTherapeutischeKoloskopie>
<OPSCodeEndoskopischePrimaertherapie></OPSCodeEndoskopischePrimaertherapie>
</EndoskopischePrimaertherapie>
<ChirurgischePrimaertherapie>
<ASAKlassifikation></ASAKlassifikation>
<DatumOperativeTumorentfernung></DatumOperativeTumorentfernung>
<OPSCodesChirurgischePrimaertherapie></OPSCodesChirurgischePrimaertherapie>
<NotfallOderElektiveingriff></NotfallOderElektiveingriff>
<Erstoperateur></Erstoperateur>
<Zweitoperateur></Zweitoperateur>
<AnastomoseDurchgefuehrt></AnastomoseDurchgefuehrt>
<TMEDurchgefuehrt></TMEDurchgefuehrt>
<PostoperativeWundinfektion></PostoperativeWundinfektion>
<DatumPostoperativeWundinfektion></DatumPostoperativeWundinfektion>
<AufgetretenAnastomoseninsuffizienz></AufgetretenAnastomoseninsuffizienz>
<AnastomoseninsuffizienzInterventionspflichtig></AnastomoseninsuffizienzInterventionspflichtig>
<DatumInterventionspflichtigeAnastomoseninsuffizienz></DatumInterventionspflichtigeAnastomoseninsuffizienz>
<Revisionseingriff></Revisionseingriff>
<DatumRevisionseingriff></DatumRevisionseingriff>
<OPmitStoma></OPmitStoma>
<Stomaangezeichnet></Stomaangezeichnet>
</ChirurgischePrimaertherapie>
<PostoperativeHistologieStaging>
<pT></pT>
<pN></pN>
<postM></postM>
<Grading></Grading>
<ICDOHistologiePostoperative></ICDOHistologiePostoperative>
<PSRLokalNachAllenOPs></PSRLokalNachAllenOPs>
<PSRGesamtNachPrimaertherapie></PSRGesamtNachPrimaertherapie>
<GueteDerMesorektumresektion></GueteDerMesorektumresektion>
<AnzahlDerUntersuchtenLymphknoten></AnzahlDerUntersuchtenLymphknoten>
<AbstandAboralerTumorrand></AbstandAboralerTumorrand>
<AbstandZirkumferentiellerTumorrand></AbstandZirkumferentiellerTumorrand>
</PostoperativeHistologieStaging>
<PostoperativeTumorkonferenz>
<VorstellungPostoperativeTumorkonferenz></VorstellungPostoperativeTumorkonferenz>
<EmpfehlungPostoperativeTumorkonferenz></EmpfehlungPostoperativeTumorkonferenz>
</PostoperativeTumorkonferenz>
<Lebermetastasen>
<LebermetastasenVorhanden></LebermetastasenVorhanden>
<LebermetastasenAusschliesslich></LebermetastasenAusschliesslich>
<PrimaereLebermetastasenresektion></PrimaereLebermetastasenresektion>
<BedingungenSenkundaereLebermetastasenresektion></BedingungenSenkundaereLebermetastasenresektion>
<SekundaereLebermetastasenresektion></SekundaereLebermetastasenresektion>
</Lebermetastasen>
<PraeoperativeStrahlentherapie>
<EmpfehlungPraeoperativeStrahlentherapie></EmpfehlungPraeoperativeStrahlentherapie>
<DatumEmpfehlungPraeoperativeStrahlentherapie></DatumEmpfehlungPraeoperativeStrahlentherapie>
<TherapiezeitpunktPraeoperativeStrahlentherapie></TherapiezeitpunktPraeoperativeStrahlentherapie>
<TherapieintentionPraeoperativeStrahlentherapie></TherapieintentionPraeoperativeStrahlentherapie>
<GruendeFuerNichtdurchfuehrungPraeoperativeStrahlentherapie></GruendeFuerNichtdurchfuehrungPraeoperativeStrahlentherapie>
<DatumBeginnPraeoperativeStrahlentherapie></DatumBeginnPraeoperativeStrahlentherapie>
<DatumEndePraeoperativeStrahlentherapie></DatumEndePraeoperativeStrahlentherapie>
<GrundDerBeendigungDerPraeoperativeStrahlentherapie></GrundDerBeendigungDerPraeoperativeStrahlentherapie>
</PraeoperativeStrahlentherapie>
<PostoperativeStrahlentherapie>
<EmpfehlungPostoperativeStrahlentherapie></EmpfehlungPostoperativeStrahlentherapie>
<DatumEmpfehlungPostoperativeStrahlentherapie></DatumEmpfehlungPostoperativeStrahlentherapie>
<TherapiezeitpunktPostoperativeStrahlentherapie></TherapiezeitpunktPostoperativeStrahlentherapie>
<TherapieintentionPostoperativeStrahlentherapie></TherapieintentionPostoperativeStrahlentherapie>
<GruendeFuerNichtdurchfuehrungPostoperativeStrahlentherapie></GruendeFuerNichtdurchfuehrungPostoperativeStrahlentherapie>
<DatumBeginnPostoperativeStrahlentherapie></DatumBeginnPostoperativeStrahlentherapie>
<DatumEndePostoperativeStrahlentherapie></DatumEndePostoperativeStrahlentherapie>
<GrundDerBeendigungDerPostoperativeStrahlentherapie></GrundDerBeendigungDerPostoperativeStrahlentherapie>
</PostoperativeStrahlentherapie>
<PraeoperativeChemotherapie>
<EmpfehlungPraeoperativeChemotherapie></EmpfehlungPraeoperativeChemotherapie>
<DatumEmpfehlungPraeoperativeChemotherapie></DatumEmpfehlungPraeoperativeChemotherapie>
<TherapiezeitpunktPraeoperativeChemotherapie></TherapiezeitpunktPraeoperativeChemotherapie>
<TherapieintentionPraeoperativeChemotherapie></TherapieintentionPraeoperativeChemotherapie>
<GruendeFuerNichtdurchfuehrungPraeoperativeChemotherapie></GruendeFuerNichtdurchfuehrungPraeoperativeChemotherapie>
<DatumBeginnPraeoperativeChemotherapie></DatumBeginnPraeoperativeChemotherapie>
<DatumEndePraeoperativeChemotherapie></DatumEndePraeoperativeChemotherapie>
<GrundDerBeendigungDerPraeoperativeChemotherapie></GrundDerBeendigungDerPraeoperativeChemotherapie>
</PraeoperativeChemotherapie>
<PostoperativeChemotherapie>
<EmpfehlungPostoperativeChemotherapie></EmpfehlungPostoperativeChemotherapie>
<DatumEmpfehlungPostoperativeChemotherapie></DatumEmpfehlungPostoperativeChemotherapie>
<TherapiezeitpunktPostoperativeChemotherapie></TherapiezeitpunktPostoperativeChemotherapie>
<TherapieintentionPostoperativeChemotherapie></TherapieintentionPostoperativeChemotherapie>
<GruendeFuerNichtdurchfuehrungPostoperativeChemotherapie></GruendeFuerNichtdurchfuehrungPostoperativeChemotherapie>
<DatumBeginnPostoperativeChemotherapie></DatumBeginnPostoperativeChemotherapie>
<DatumEndePostoperativeChemotherapie></DatumEndePostoperativeChemotherapie>
<GrundDerBeendigungDerPostoperativeChemotherapie></GrundDerBeendigungDerPostoperativeChemotherapie>
</PostoperativeChemotherapie>
<BestSupportiveCare></BestSupportiveCare>
<Prozess>
<DatumStudie></DatumStudie>
<Studientyp></Studientyp>
<PsychoonkologischeBetreuung></PsychoonkologischeBetreuung>
<BeratungSozialdienst></BeratungSozialdienst>
<GenetischeBeratungEmpfohlen></GenetischeBeratungEmpfohlen>
<GenetischeBeratungErhalten></GenetischeBeratungErhalten>
<ImmunhistochemischeUntersuchungAufMSI></ImmunhistochemischeUntersuchungAufMSI>
</Prozess>
<FollowUp>
<DatumFollowUp></DatumFollowUp>
<LokoregionaeresRezidiv></LokoregionaeresRezidiv>
<LymphknotenRezidiv></LymphknotenRezidiv>
<Fernmetastasen></Fernmetastasen>
<Zweittumor></Zweittumor>
<Verstorben></Verstorben>
<QuelleFollowUp></QuelleFollowUp>
</FollowUp>
</Fall>
</Patient>
First, I have to navigate to certain nodes (for example "DatumXML") and enter a value.
Second, I have to iterate all subnodes of certain nodes (for example Stammdaten) and enter values.

I think the SimpleXMLIterator is going to be your best bet. You didn't quite explain the structure of your XML, but you should be able to do something like:
$iterator = new SimpleXMLIterator($xml);
for ($iterator->rewind(); $iterator->valid(); $iterator->next()) {
$node = $iterator->key();
// Get data from database based on node name
$iterator->{$node} = $data;
}
$finished_xml = $iterator->asXML();
If you're structure is more complex, you should be able to adapt this to what you need. Just remember that a SimpleXMLIterator is a SimpleXMLElement and you can use the same methods and techniques.

Related

PHP -> Curl -> Soap Response (Get data from xml tags)

I have a Curl response with Soap XML data.
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Header/><SOAP-ENV:Body><ns2:GetAccountMovementsResponseIo xmlns:ns2="http://www.mygemini.com/schemas/mygemini">
<ns2:result>
<ns2:pager>
<ns2:pageIndex>0</ns2:pageIndex>
<ns2:pageSize>700</ns2:pageSize>
</ns2:pager>
<ns2:totalCount>3</ns2:totalCount>
</ns2:result>
<ns2:accountMovement>
<ns2:movementId>002147575330.2</ns2:movementId>
<ns2:paymentId>95694091</ns2:paymentId>
<ns2:externalPaymentId>2147575330</ns2:externalPaymentId>
<ns2:debitCredit>1</ns2:debitCredit>
<ns2:valueDate>2018-12-13T00:00:00+04:00</ns2:valueDate>
<ns2:description>გადარიცხვა პირად ანგარიშზე</ns2:description>
<ns2:amount>
<ns2:amount>10000</ns2:amount>
<ns2:currency>GEL</ns2:currency>
</ns2:amount>
<ns2:accountNumber>GE44TB7142536020100005</ns2:accountNumber>
<ns2:accountName>კლიენტი:1425</ns2:accountName>
<ns2:additionalInformation>კლიენტი:1425, 123456786, TBCBGE22, GE17TB7142536020100006</ns2:additionalInformation>
<ns2:documentDate>2018-12-13T00:00:00+04:00</ns2:documentDate>
<ns2:documentNumber>1544698824</ns2:documentNumber>
<ns2:partnerAccountNumber>GE17TB7142536020100006</ns2:partnerAccountNumber>
<ns2:partnerName>კლიენტი:1425, 123456786</ns2:partnerName>
<ns2:partnerTaxCode>123456786</ns2:partnerTaxCode>
<ns2:partnerBankCode>TBCBGE22</ns2:partnerBankCode>
<ns2:partnerBank>სს თიბისი ბანკი</ns2:partnerBank>
<ns2:taxpayerCode>123456786</ns2:taxpayerCode>
<ns2:taxpayerName>კლიენტი:1425, 123456786</ns2:taxpayerName>
<ns2:operationCode>GII</ns2:operationCode>
<ns2:partnerDocumentType>0</ns2:partnerDocumentType>
<ns2:statusCode>3</ns2:statusCode>
<ns2:transactionType>1</ns2:transactionType>
</ns2:accountMovement>
<ns2:accountMovement>
<ns2:movementId>002147575330.1</ns2:movementId>
<ns2:paymentId>95694091</ns2:paymentId>
<ns2:externalPaymentId>2147575330</ns2:externalPaymentId>
<ns2:debitCredit>0</ns2:debitCredit>
<ns2:valueDate>2018-12-13T00:00:00+04:00</ns2:valueDate>
<ns2:description>გადარიცხვა პირად ანგარიშზე</ns2:description>
<ns2:amount>
<ns2:amount>10000</ns2:amount>
<ns2:currency>GEL</ns2:currency>
</ns2:amount>
<ns2:accountNumber>GE17TB7142536020100006</ns2:accountNumber>
<ns2:accountName>კლიენტი:1425, 123456786</ns2:accountName>
<ns2:additionalInformation>კლიენტი:1425, TBCBGE22, GE44TB7142536020100005</ns2:additionalInformation>
<ns2:documentDate>2018-12-13T00:00:00+04:00</ns2:documentDate>
<ns2:documentNumber>1544698824</ns2:documentNumber>
<ns2:partnerAccountNumber>GE44TB7142536020100005</ns2:partnerAccountNumber>
<ns2:partnerName>კლიენტი:1425</ns2:partnerName>
<ns2:partnerTaxCode>123456786</ns2:partnerTaxCode>
<ns2:partnerBankCode>TBCBGE22</ns2:partnerBankCode>
<ns2:partnerBank>სს თიბისი ბანკი</ns2:partnerBank>
<ns2:taxpayerCode>123456786</ns2:taxpayerCode>
<ns2:taxpayerName>კლიენტი:1425, 123456786</ns2:taxpayerName>
<ns2:operationCode>GII</ns2:operationCode>
<ns2:partnerDocumentType>0</ns2:partnerDocumentType>
<ns2:statusCode>3</ns2:statusCode>
<ns2:transactionType>1</ns2:transactionType></ns2:accountMovement>
<ns2:accountMovement><ns2:movementId>002147575329.2</ns2:movementId>
<ns2:externalPaymentId>2147575329</ns2:externalPaymentId>
<ns2:debitCredit>1</ns2:debitCredit>
<ns2:valueDate>2018-12-13T00:00:00+04:00</ns2:valueDate>
<ns2:description>ანგარიშზე თანხის შეტანა</ns2:description><ns2:amount>
<ns2:amount>100000</ns2:amount><ns2:currency>GEL</ns2:currency></ns2:amount>
<ns2:accountNumber>GE17TB7142536020100006</ns2:accountNumber>
<ns2:accountName>კლიენტი:1425</ns2:accountName>
<ns2:additionalInformation>სახელი:3928462 გვარი3928462</ns2:additionalInformation>
<ns2:documentDate>2018-12-13T00:00:00+04:00</ns2:documentDate>
<ns2:documentNumber>63946130</ns2:documentNumber>
<ns2:partnerAccountNumber>GE78TB0000000000060000</ns2:partnerAccountNumber>
<ns2:partnerName>სახელი:3928462 გვარი3928462</ns2:partnerName>
<ns2:partnerTaxCode>00000000000</ns2:partnerTaxCode>
<ns2:partnerBankCode>TBCBGE22</ns2:partnerBankCode><ns2:partnerBank>ს.ს. „თიბისი ბანკი”</ns2:partnerBank>
<ns2:operationCode>01</ns2:operationCode>
<ns2:partnerPersonalNumber>00000000000</ns2:partnerPersonalNumber>
<ns2:partnerDocumentType>6</ns2:partnerDocumentType>
<ns2:partnerDocumentNumber>DC102086</ns2:partnerDocumentNumber>
<ns2:statusCode>3</ns2:statusCode>
<ns2:transactionType>20</ns2:transactionType>
</ns2:accountMovement>
</ns2:GetAccountMovementsResponseIo>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
I would like to get data inside tags one by one
<ns2:paymentId>, <ns2:externalPaymentId>, <ns2:debitCredit> etc.
Kindly note that this is dummy data of a bank statement, and in real life responses have multiple tags with the same name per each transaction. For example, if there are 11 transactions, there will be 11 <ns2:paymentId> tags and I need to get data one by one.
Using SimpleXML you can read the code and the data much easier. The only thing is that you need to respect the namespaces. So first register the ns2 namespace so that you can then you can fetch the <ns2:accountMovement> elements. The loop over these, but to access the child elements in the namespace, use children("http://www.mygemini.com/schemas/mygemini") to get them into the $data variable, then each access is via this (i.e. $data->paymentId)...
$xml = simplexml_load_string($xmlContent);
$xml->registerXPathNamespace("ns2", "http://www.mygemini.com/schemas/mygemini");
$movements = $xml->xpath("//ns2:GetAccountMovementsResponseIo/ns2:accountMovement");
foreach ( $movements as $accMove ) {
$data = $accMove->children("http://www.mygemini.com/schemas/mygemini");
echo "paymentId ->".$data->paymentId.PHP_EOL;
echo "externalPaymentId ->".$data->externalPaymentId.PHP_EOL;
echo "debitCredit ->".$data->debitCredit.PHP_EOL;
}

SimpleXML node parse Lyric Wikia REST API

Taken from the Lyrics Wikia REST api XML response http://api.wikia.com/wiki/LyricWiki_API/REST , how do I parse this? I wasn't able to find any examples of other people working with these nodes.
http://lyrics.wikia.com/api.php?func=getArtist&artist=Linkin_Park&fmt=xml
<getArtistResponse>
<artist>Linkin Park</artist>
<albums>
<album>Xero</album>
<year>1997</year>
<amazonLink>
http://www.amazon.com/exec/obidos/redirect?link_code=ur2&tag=wikia-20&camp=1789&creative=9325&path=external-search%3Fsearch-type=ss%26index=music%26keyword=Linkin%20Park%20Xero
</amazonLink>
<songs>
<item>Rhinestone</item>
<item>Reading My Eyes</item>
<item>Fuse</item>
<item>Stick N' Move</item>
</songs>
<album>Hybrid Theory</album>
<year>1999</year>
<amazonLink>
http://www.amazon.com/exec/obidos/redirect?link_code=ur2&tag=wikia-20&camp=1789&creative=9325&path=external-search%3Fsearch-type=ss%26index=music%26keyword=Linkin%20Park%20Hybrid%20Theory
</amazonLink>
<songs>
<item>Carousel</item>
<item>Technique</item>
<item>Step Up</item>
<item>And One</item>
<item>High Voltage (EP Version)</item>
<item>Part Of Me</item>
<item>High Voltage</item>
<item>Esaul (Underground EP)</item>
</songs>
<album>Hybrid Theory</album>
<year>2000</year>
<amazonLink>
http://www.amazon.com/exec/obidos/redirect?link_code=ur2&tag=wikia-20&camp=1789&creative=9325&path=external-search%3Fsearch-type=ss%26index=music%26keyword=Linkin%20Park%20Hybrid%20Theory
</amazonLink>
<songs>
<item>Papercut</item>
<item>One Step Closer</item>
<item>With You</item>
<item>Points Of Authority</item>
<item>Crawling</item>
<item>Runaway</item>
<item>By Myself</item>
<item>In The End</item>
<item>A Place For My Head</item>
<item>Forgotten</item>
<item>Cure For The Itch</item>
<item>Pushing Me Away</item>
<item>My December</item>
<item>High Voltage</item>
<item>Papercut</item>
<item>Papercut</item>
<item>Points Of Authority</item>
<item>A Place For My Head</item>
</songs>
I'd like for these to look like the following with links to each song node:
Xero 1997: Rhinestone Reading My Eyes Fuse Stick N' Move
Hybrid Theory 1999: Carousel Technique Step Up Etc..
I've been able to get the song->items with `
foreach ($xml->albums->songs as $entry){
$item0 = $entry->item[0];
$item1 = $entry->item[1];
$item2 = $entry->item[2];
$item3 = $entry->item[3];
$item4 = $entry->item[4];
etc
But I have been unsuccessful in grabbing each album and year beyond the first.
Thank you for the help. :)

Populate Flex ComboBox from XML from PHP

I'm having trouble populating a combobox from an XML response. Here is the XML that I am receiving:
<distros>
<entry>
<distro>CentOS</distro>
<distro>Debian</distro>
<distro>Other</distro>
<distro>Sabayon</distro>
<distro>Ubuntu</distro>
<distro>VMware</distro>
<distro>Windows</distro>
</entry>
</distros>
So probably the most basic form of XML ever!
and here is the flex code:
private function getDistros():void
{
httpReq = new HTTPService;
httpReq.url = 'http://myserver/xml.php';
httpReq.resultFormat = 'e4x';
httpReq.method = 'GET';
httpReq.addEventListener(ResultEvent.RESULT, popDistros);
httpReq.send( null );
}
private function popDistros(event:ResultEvent):void
{
if(event.result != "")
{
// Set the data to the XMLListCollection for lookup
myXmlCollection= new XMLListCollection(event.result.entry);
// Bind the ListCollection to the comboBox
Alert.show(myXmlCollection.toString());
distroCombo.dataProvider = myXmlCollection.toString();
}
}
and the MXML:
<mx:ControlBar x="139" y="10" width="266" height="358" verticalAlign="top" horizontalAlign="left" direction="vertical">
<mx:ComboBox id="distroCombo" labelField="distro"></mx:ComboBox>
<mx:ComboBox id="imageCombo"></mx:ComboBox>
<mx:Button label="Download"/>
</mx:ControlBar>
The XML comes back fine in the Alert but the comboBox won't populate and I have tried this so many different ways now, anyone got any suggestions? Have I just been staring at it far too long?
if the result (event.result) is XML, then It should wotk like this: (it differs with .distro in the end compared to yours)
myXmlCollection = new XMLListCollection(event.result.entry.distro);
...this should create valid data in myXmlCollection
But then also this row is wrong:
distroCombo.dataProvider = myXmlCollection.toString();
it creates just one item in dataProvider of type string, (Just BTW: if you would have used spark combobox, you would have get compile error at this row).
just use this instead:
distroCombo.dataProvider = myXmlCollection;
And also note, that you can see correct result in the Alert, but it does not say if the data are of correct type, coz Alert evertyhing converts to string :)

Data structure to save nested XML based data

I obtain this type of response via curl:
<ArrayOfServerFile>
<ServerFile>
...
<FileType>Folder</FileType>
<Identifier>x123</Identifier>
<Name>Client Templates</Name>
...
</ServerFile>
<ServerFile>
...
<FileType>XpressDox Template</FileType>
<Identifier>y456</Identifier>
<Name>contact-information.xdtpl</Name>
...
</ServerFile>
...
</ArrayOfServerFile>
I want to save this info in a tree-like data structure.
I have tried something like this:
// Pseudo-code:
function run_procedure()
{
get XML data via curl
if FileType == 'Folder'
save name and other useful data into $tree_like_data_structure
run_procedure() // recursive call
else if FileType == 'XpressDox Template'
save name and other useful data into $tree_like_data_structure
}
var_dump($tree_like_data_structure);
The idea is to represent saved data like this:
[0][0] -> data
[1][0] -> data
[1][1] -> data
[1][2] -> [2][0] -> data
[2][1] -> data
[1][3] -> data
I am pretty sure that this is not so hard to accomplish but I have lost a lot of time without success. Any tip is very welcome. Thanks.-
EDIT 1
My main concern is how obtain [depth][element] indexes and how level data (type, name, content, etc).
EDIT 2
Basically this is a recursive programming problem. Maybe it can be done via while statements more easily than with a recursive function?
Try using SimpleXML with the DOM to create your array.
$dom = new DOMDocument;
$dom->loadXML('
<ArrayOfServerFile>
<ServerFile>
<FileType>Folder</FileType>
<Identifier>x123</Identifier>
<Name>Client Templates</Name>
</ServerFile>
</ArrayOfServerFile>');
if (!$dom) {
echo 'Error while parsing the document';
exit;
}
$s = simplexml_import_dom($dom);
echo $s->ServerFile[0]->FileType;

Missing items using simpleXML in PHP

I have this XML output. I am feeding it into simpleXML in PHP. I am trying to retrieve all stands, plots, and trees. For some reason, I am only getting the plots in the first stand and not the second. The same for trees, I am only getting the tree backs in the first stand. The code that I am using is posted below the XML. I have tried many different ways to hit these sections and no luck .
<Tracts>
<tract>
<tract>tract1</tract>
<county>Glynn</county>
<state>GA</state>
<name>Garrett</name>
<owner>Bob</owner>
<date>Nov 6, 2011</date>
<stands>
<Stand>
<stand>1</stand>
<age>12</age>
<thinned>true</thinned>
<thinYear>2007</thinYear>
<species>PL Lob</species>
<cruiser>me</cruiser>
<hPlotSize>50th Acre</hPlotSize>
<pPlotSize>50th Acre</pPlotSize>
<treeType>None</treeType>
<fixedOrPrism>5</fixedOrPrism>
<plots>
<Plot>
<plotNum>5</plotNum>
<pPMStems>12</pPMStems>
<hPMStems>12</hPMStems>
<pPMHt>12</pPMHt>
<hPMHt>12</hPMHt>
<pMStems>12</pMStems>
<hMStems>12</hMStems>
<pMHt>0</pMHt>
<hMHt>12</hMHt>
<pHtCrown>0</pHtCrown>
<trees>
<Tree>
<treeNum>3</treeNum>
<DBH>18</DBH>
<species>LOB</species>
<type>CROP</type>
<merch>12</merch>
<htToCrown>9</htToCrown>
<merchLogs>1.0</merchLogs>
<defects>
<string>CRON</string>
<string>SCRAPE</string>
</defects>
</Tree>
<Tree>
<treeNum>3</treeNum>
<DBH>18</DBH>
<species>LOB</species>
<type>CROP</type>
<merch>12</merch>
<htToCrown>9</htToCrown>
<merchLogs>1.0</merchLogs>
<defects>
<string>CRON</string>
<string>SCRAPE</string>
</defects>
</Tree>
<Tree>
<treeNum>3</treeNum>
<DBH>18</DBH>
<species>LOB</species>
<type>CROP</type>
<merch>12</merch>
<htToCrown>9</htToCrown>
<merchLogs>1.0</merchLogs>
<defects>
<string>CRON</string>
<string>SCRAPE</string>
</defects>
</Tree>
</trees>
</Plot>
<Plot>
<plotNum>9</plotNum>
<pPMStems>3</pPMStems>
<hPMStems>3</hPMStems>
<pPMHt>3</pPMHt>
<hPMHt>3</hPMHt>
<pMStems>3</pMStems>
<hMStems>3</hMStems>
<pMHt>0</pMHt>
<hMHt>3</hMHt>
<pHtCrown>0</pHtCrown>
<trees />
</Plot>
</plots>
</Stand>
<Stand>
<stand>2</stand>
<age>20</age>
<thinned>false</thinned>
<thinYear>0</thinYear>
<species>PL Lob</species>
<cruiser>me</cruiser>
<hPlotSize>50th Acre</hPlotSize>
<pPlotSize>10th Acre</pPlotSize>
<treeType>Fixed</treeType>
<fixedOrPrism>100%</fixedOrPrism>
<plots>
<Plot>
<plotNum>2</plotNum>
<pPMStems>12</pPMStems>
<hPMStems>20</hPMStems>
<pPMHt>32</pPMHt>
<hPMHt>16</hPMHt>
<pMStems>21</pMStems>
<hMStems>7</hMStems>
<pMHt>0</pMHt>
<hMHt>13</hMHt>
<pHtCrown>0</pHtCrown>
<trees>
<Tree>
<treeNum>1</treeNum>
<DBH>10</DBH>
<species>LOB</species>
<type>CROP</type>
<merch>12</merch>
<htToCrown>16</htToCrown>
<merchLogs>4.5</merchLogs>
<defects>
<string>CRON</string>
<string>OTHER</string>
</defects>
</Tree>
</trees>
</Plot>
</plots>
</Stand>
</stands>
</tract>
</Tracts>
foreach($xml->tract->stands->Stand->plots->Plot as $plot)
{
echo $plot->plotNum;
}
echo '<br><br>';
foreach ($xml->tract->stands->Stand->plots->Plot->trees->Tree as $tree)
{
echo $tree->treeNum;
}
The variable $xml->tract->stands->Stand->plots->Plot will only ever reference the first Stand element - think of the document as a set of nested arrays.
SimpleXML assumes that if you mention an element name without looping or indexing into it, you want the first element of that name. In other words, it's the same as writing foreach ( $xml->tract[0]->stands[0]->Stand[0]->plots[0]->Plot ) ...
So you need to nest your foreach loops:
foreach($xml->tract->stands->Stand as $stand)
{
foreach($stand->plots->Plot as $plot)
{
echo $plot->plotNum;
foreach ( $plot->trees->Tree as $tree )
{
echo $tree->treeNum;
}
}
}

Categories