I am working with XML and php. I am trying to get an array of PHP result to this XML format with two <customer> customers, I can get 1 but dont know how to do it for 2 customers in an array.
<?xml version="1.0"?>
<NewSLSCase>
<Identification CientNo="4xxx" CLientBatchNo="1" IJBatchNo="1" HubNo="201048" ClientEmailAddress1="etunimi.sukunimi#yritys.fi" ClientEmailAddress2="etunimi.sukunimi#yritys.fi"/>
<LedgerSet>
<Ledger ProductionUnit="04" LedgerNo="4xxxxx">
<CustomerSet>
<Customer No="123456" Name="Farhana" Address1="Myhouse" ZipCode="40100" City="Vantaa" LanguageCode="FIN" CountryCode="FI" VatNo="01011-111A" TypeCode="C"/>
<Customer No="123457" Name="Asiakas Anna" Address1="Asiakastie 2" ZipCode="00100" City=" Helsinki" LanguageCode="FIN" CountryCode="FI" VATNo="010111-111A" TypeCode="C"/>
</CustomerSet>
<InvoiceSet>
<Invoice InvoiceNo="123456"/>
<InvoiceHeader InvoiceHeaderType="L" InvoiceCustomerNo="123456" InvoiceCurrency="EUR" InvoiceDate="2011-04-08" InvoiceDueDate="2011-05-15" InvoiceAmount="57.00" ClientOCRReference="908000101800031186" InvoiceReferenceText3="150,00" InvoiceReferenceText4="Laskuille tulostuva" InvoiceReferenceText5="IBAN" InvoiceReferenceText6="BIC"/>
</InvoiceSet>
</Ledger>
</LedgerSet>
</NewSLSCase>
I wrote the codes for just getting one ` but adding another one is something I am truly not sure off.
Here is the array, did not copy the whole thing since its big, but I am using a small part of it for testing.
array(2) (
[0] => stdClass object {
ID => (string) 177835
currency => (string) Asiakas Anna
type => (string) Asiakastie 2
}
[1] => stdClass object {
ID => (string) 177840
Name=> (string) Farhana
Address=> (string) Myhouse
.....
Here is the whole XML format
$result = $this->invoice_page->getInvoiceByID('20241'); //this is the array
$xml = new DomDocument('1.0');
$xml->formatOutput = true;
$NewSLSCase = $xml->createElement("NewSLSCase");
$xml->appendChild($NewSLSCase);
$Identification = $xml->createElement("Identification");
$Identification->setAttribute("CientNo","4xxx");
$Identification->setAttribute("CLientBatchNo", "1");
$Identification->setAttribute("CLientBatchNo", "1");
$Identification->setAttribute("IJBatchNo", "1");
$Identification->setAttribute("HubNo", "201048");
$Identification->setAttribute("ClientEmailAddress1", "etunimi.sukunimi#yritys.fi");
$Identification->setAttribute("ClientEmailAddress2", "etunimi.sukunimi#yritys.fi");
$NewSLSCase->appendChild($Identification);
$LedgerSet = $xml->createElement("LedgerSet");
$NewSLSCase->appendChild($LedgerSet);
$Ledger = $xml->createElement("Ledger");
$Ledger->setAttribute("ProductionUnit","04");
$Ledger->setAttribute("LedgerNo", "4xxxxx");
$LedgerSet->appendChild($Ledger);
$CustomerSet = $xml->createElement("CustomerSet");
$Ledger->appendChild($CustomerSet);
$Customer = $xml->createElement("Customer");
$Customer->setAttribute("No","123456");
$Customer->setAttribute("Name", $result['Fullname']);
$Customer->setAttribute("Address1", $result['Address_street']);
$Customer->setAttribute("ZipCode", $result['Address_zip']);
$Customer->setAttribute("City",$result['Address_city']);
$Customer->setAttribute("LanguageCode", "FIN");
$Customer->setAttribute("CountryCode","FI");
$Customer->setAttribute("VatNo", "01011-111A");
$Customer->setAttribute("TypeCode","C");
$CustomerSet->appendChild($Customer);
$InvoiceSet = $xml->createElement("InvoiceSet");
$Ledger->appendChild($InvoiceSet);
$Invoice = $xml->createElement("Invoice");
$Invoice->setAttribute("InvoiceNo","123456");
$InvoiceSet->appendChild($Invoice);
$InvoiceHeader = $xml->createElement("InvoiceHeader");
$InvoiceHeader->setAttribute("InvoiceHeaderType", "L");
$InvoiceHeader->setAttribute("InvoiceCustomerNo","123456");
$InvoiceHeader->setAttribute("InvoiceCurrency", "EUR");
$InvoiceHeader->setAttribute("InvoiceDate","2011-04-08");
$InvoiceHeader->setAttribute("InvoiceDueDate", "2011-05-15");
$InvoiceHeader->setAttribute("InvoiceAmount","57.00");
$InvoiceHeader->setAttribute("ClientOCRReference", "908000101800031186");
$InvoiceHeader->setAttribute("InvoiceReferenceText3","150,00");
$InvoiceHeader->setAttribute("InvoiceReferenceText4","Laskuille tulostuva");
$InvoiceHeader->setAttribute("InvoiceReferenceText5",$result['IBAN']);
$InvoiceHeader->setAttribute("InvoiceReferenceText6",$result['BIC']);
$InvoiceSet->appendChild($InvoiceHeader);
echo "<xmp>".$xml->saveXML()."</xmp>";
What the above code, gives me is this
<?xml version="1.0"?>
<NewSLSCase>
<Identification CientNo="4xxx" CLientBatchNo="1" IJBatchNo="1" HubNo="201048" ClientEmailAddress1="etunimi.sukunimi#yritys.fi" ClientEmailAddress2="etunimi.sukunimi#yritys.fi"/>
<LedgerSet>
<Ledger ProductionUnit="04" LedgerNo="4xxxxx">
<CustomerSet>
<Customer No="123456" Name="Farhana" Address1="Myhouse" ZipCode="40100" City="Vantaa" LanguageCode="FIN" CountryCode="FI" VatNo="01011-111A" TypeCode="C"/>
</CustomerSet>
<InvoiceSet>
<Invoice InvoiceNo="123456"/>
<InvoiceHeader InvoiceHeaderType="L" InvoiceCustomerNo="123456" InvoiceCurrency="EUR" InvoiceDate="2011-04-08" InvoiceDueDate="2011-05-15" InvoiceAmount="57.00" ClientOCRReference="908000101800031186" InvoiceReferenceText3="150,00" InvoiceReferenceText4="Laskuille tulostuva" InvoiceReferenceText5="IBAN" InvoiceReferenceText6="BIC"/>
</InvoiceSet>
</Ledger>
</LedgerSet>
</NewSLSCase>
I have no clue how to add a foreach to get two customers information.
Use foreach loop through customers:
foreach ($customersArray as $customerData) {
$Customer = $xml->createElement("Customer");
$Customer->setAttribute("No",$customerData->ID);
//set all attributes like that
$CustomerSet->appendChild($Customer);
}
Related
I am trying to read XML data in PHP. The XML data is coming from an API whose link is the following: https://seekingalpha.com/api/sa/combined/AAPL.xml
I just need News Headline, News Link , Published Date and Author Name of the first five news from the API. To do this, I am using the following PHP code:
$note = "https://seekingalpha.com/api/sa/combined/".$symbolValue.".xml";
$xml=simplexml_load_file($note);
$jsonArray = array();
for ($i=0; $i<5; $i++) {
$newsHeadline = $xml->channel->item[$i]->title->__toString();
$newsLink = $xml->channel->item[$i]->link->__toString();
$publishedDate = $xml->channel->item[$i]->pubDate->__toString();
$authorName = $xml->channel->item[$i]->sa:author_name->__toString();
$temp = array('Title' => $newsHeadline, 'Link' => $newsLink,'Publish'=>$publishedDate,'Author'=>$authorName);
array_push($jsonArray,$temp);
}
$jsonNews = json_encode($jsonArray);
$completeData[9] = $jsonNews;
In the above code, $note contains the link to the API. The $symbolValue is the value which I am getting from the front end. My code works absolutely until I access the author name ie. The following line of code:
$authorName = $xml->channel->item[$i]->sa:author_name->__toString();
I am getting the following error:
Parse error: syntax error, unexpected ':' in /home/File/Path
It seems like I am not supposed to use the ":" for fetching the author name.
So, how do I get the user name and put it in the $temp such that the Tag for the author name is "Author"?
Please have a look at the API to get an idea about the XML file.
The children() method supports an argument for the namespace you want to read. This is required when you want to read elements which are not in the current/default namespace.
$xmldata = <<<'XML'
<?xml version="1.0"?>
<foobar xmlns:x="http://example.org/">
<abc>test</abc>
<x:def>content</x:def>
</foobar>
XML;
$xml = new Simplexmlelement($xmldata);
$other = $xml->children('http://example.org/');
var_dump((string)$other->def);
This will output the value "content", but using the expression $xml->def will not because that is not in the current/default namespace.
If you property contains for example a :, you could use curly braces
->{'sa:author_name'}
The values you are looking for are in the https://seekingalpha.com/api/1.0 namespace.
You could use the children of the SimpleXMLElement and add te namespace:
$authorName = (string)$xml->channel->item[$i]->children('https://seekingalpha.com/api/1.0')->{'author_name'};
Or you could use xpath.
$authorName = (string)$xml->channel->item[$i]->xpath('sa:author_name')[0];
For example:
$jsonArray = array();
for ($i = 0; $i < 5; $i++) {
$newsHeadline = $xml->channel->item[$i]->title->__toString();
$newsLink = $xml->channel->item[$i]->link->__toString();
$publishedDate = $xml->channel->item[$i]->pubDate->__toString();
$authorName = (string)$xml->channel->item[$i]->xpath('sa:author_name')[0];
// or xpath
// $authorName = (string)$xml->channel->item[$i]->children('https://seekingalpha.com/api/1.0')->{'author_name'};
$temp = array('Title' => $newsHeadline, 'Link' => $newsLink, 'Publish' => $publishedDate, 'Author' => $authorName);
array_push($jsonArray, $temp);
}
$jsonNews = json_encode($jsonArray);
print_r($jsonArray);
Will give you:
Array
(
[0] => Array
(
[Title] => Apple acknowledges iPhone X issue in some devices, plans fix
[Link] => https://seekingalpha.com/symbol/AAPL/news?source=feed_symbol_AAPL
[Publish] => Fri, 10 Nov 2017 12:04:42 -0500
[Author] => Brandy Betz
)
etc...
I am trying to use PHP to read a large XML file (gzipped). The file consists of repeated products (actually books). Each book has 1 or more contributors. This is an example of a product.
<Product>
<ProductIdentifier>
<IDTypeName>EAN.UCC-13</IDTypeName>
<IDValue>9999999999999</IDValue>
</ProductIdentifier>
<Contributor>
<SequenceNumber>1</SequenceNumber>
<ContributorRole>A01</ContributorRole>
<PersonNameInverted>Bloggs, Joe</PersonNameInverted>
</Contributor>
<Contributor>
<SequenceNumber>2</SequenceNumber>
<ContributorRole>A01</ContributorRole>
<PersonNameInverted>Jones, John</PersonNameInverted>
</Contributor>
<Contributor>
<SequenceNumber>3</SequenceNumber>
<ContributorRole>B01</ContributorRole>
<PersonNameInverted>Other, An</PersonNameInverted>
</Contributor>
The output I would wish for this example is
Array
(
[1] => 9999999999999
[2] => Bloggs, Joe(A01)
[3] => Jones, John(A01)
[4] => Other, An(B01)
)
My code loads the gzipped XML file and handles the repeated sequence of products with no problem but I cannot get it to handle the repeated sequence of contributors. My code for handling the products and first contributor is shown below but I have tried various ways of looping through the contributors but cannot seem to achieve what I need. I'm a beginner with PHP and XML although an IT professional for many years.
$reader = new XMLReader();
//load the selected XML file to the DOM
if(!$reader->open("compress.zlib://filename.xml.gz","r")){
die('Failed to open file!');
}
while ($reader->read()):
if ($reader->nodeType == XMLReader::ELEMENT && $reader->name == 'Product')
{
$xml = simplexml_load_string($reader->readOuterXML());
list($result) = $xml->xpath('//ProductIdentifier[IDTypeName = "EAN.UCC-13"]');
$line[1] = (string)$result->IDValue;
list($result) = $xml->xpath('//Contributor');
$contributorname = (string)$result->PersonNameInverted;
$role = (string)$result->ContributorRole;
$line[2] = $contributorname."(".$role.")";
echo '<pre>'; print_r($line); echo '</pre>';
}
endwhile;
Since you have several contributors, you must handle it as an array and loop on them to prepare your final variable:
<?php
$reader = new XMLReader();
//load the selected XML file to the DOM
if(!$reader->open("compress.zlib://filename.xml.gz","r")){
die('Failed to open file!');
}
while ($reader->read()) {
if ($reader->nodeType == XMLReader::ELEMENT && $reader->name == 'Product') {
$xml = simplexml_load_string($reader->readOuterXML());
list($result) = $xml->xpath('//ProductIdentifier[IDTypeName = "EAN.UCC-13"]');
$line[1] = (string)$result->IDValue;
// get all contributors in an array
$contributors = $xml->xpath('//Contributor');
$i = 2;
// go through all contributors
foreach($contributors as $contributor) {
$contributorname = (string)$contributor->PersonNameInverted;
$role = (string)$contributor->ContributorRole;
$line[$i] = $contributorname."(".$role.")";
$i++;
}
echo '<pre>'; print_r($line); echo '</pre>';
}
}
This will give you the following output:
Array
(
[1] => 9999999999999
[2] => Bloggs, Joe(A01)
[3] => Jones, John(A01)
[4] => Other, An(B01)
)
EDIT: Some explanation here on what is wrong on your code. Instead of taking all the contributors, you just take the first one with list()
http://php.net/manual/en/function.list.php (assign all values of an array into variables). Since you don't know how many contributors you have (i guess...), you cannot use this.
Then you assign the first one into your $line, so you always have only the first one.
I have an XML file like so:
<GenResponse>
<Detail1></Detail1>
<Detail2></Detail>
<DataNodes>
<DataNode>
<NodeDetails1>
<node4>Parrot Musky Truck Moo</node4>
<node5>Tinker Singer Happy Fool</node5>
<node6>
<FurtherDetails>
<Node>Musky</Node>
<Node>Lorem Ipsum</Node>
</FurtherDetails>
</NodeDetails1>
<NodeDetails2>ID</NodeDetails2>
</DataNode>
<DataNode>
<NodeDetails1>
<node4>Sky Star Panet Shoe</node4>
<node5>Rusky Husky Musky Boo</node5>
</NodeDetails1>
<NodeDetails2>ID</NodeDetails2>
</DataNode>
</DataNodes>
</GenResponse>
I would like to know how I would inject a search string "Musky" to a PHP function and get back <DataNode>...</DataNode> & <DataNode>...</DataNode> back?
Essentially I would like to search a huge XML file for a string and return all the DataNode's which contain the string back.
If this is possible with SimpleXML it would be great. Else any other solution is also fine.
EDIT: Notice how "Musky" can be in different nodes under <DataNode>
use
$xmlStr = file_get_contents('data/your_XML_File.xml');
$xml = new SimpleXMLElement($xmlStr);
// seach records by tag value:
// find nodes with text
$res = $xml->xpath("node2[contains(., 'Musky')]");
print_r($res);
//For testing purpost just copy paste following code in editor , For testing , I didnt use separate xml file.
<?php
//$xmlStr = file_get_contents('test.xml');
$xmlStr = '<node1>
<node2>
<node3>
<node4>Parrot Singer Truck Moo</node4>
<node5>Tinker Musky Happy Fool</node5>
</node3>
<node7>ID</node7>
</node2>
<node2>
<node3>
<node4>Sky Star Panet Shoe</node4>
<node5>Rusky Husky Musky Boo</node5>
</node3>
<node7>ID</node7>
</node2>
</node1>';
$xml = new SimpleXMLElement($xmlStr);
// seach records by tag value:
// find nodes with text
$res = $xml->xpath("node2[contains(., 'Musky')]");
echo "<pre>";
print_r($res);
?>
It gives proper output , i tried
Array
(
[0] => SimpleXMLElement Object
(
[node3] => SimpleXMLElement Object
(
[node4] => Parrot Singer Truck Moo
[node5] => Tinker Musky Happy Fool
)
[node7] => ID
)
[1] => SimpleXMLElement Object
(
[node3] => SimpleXMLElement Object
(
[node4] => Sky Star Panet Shoe
[node5] => Rusky Husky Musky Boo
)
[node7] => ID
)
)
Use this code and you can find your search word.I have made it a function just pass your keyword and you will get your result,
function findWord($findVar)
{
$catalog = simplexml_load_file("xmlfile.xml");
$category = $catalog->node2;
$found = 0;
foreach($category as $c)
{
foreach($c->node3 as $node3)
{
$node4 = (string) ($node3->node4);
$node5 = (string) ($node3->node5);
if (stripos(strtolower($node4),strtolower($findVar)))
{
echo 'Found!!'.'<br/>';
$found++;
}
if (stripos(strtolower($node5),strtolower($findVar)))
{
echo 'Found!!'.'<br/>';
$found++;
}
}
if (stripos(strtolower((string)$c->node7),strtolower($findVar)))
{
echo 'Found!!'.'<br/>';
$found++;
}
}
if ($found == 0)
{
echo "No result";
}
}
$findVar = 'Musky';
findWord($findVar);
I'm trying to parse some items from a log of soap request XML and can't seem to figure out how to get to the innards of a SimpleXMLElement. Here's an example of the XML I'm using:
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://fedex.com/ws/rate/v9">
<SOAP-ENV:Body>
<ns1:RateRequest>
<ns1:WebAuthenticationDetail>
<ns1:UserCredential>
<ns1:Key>aaaaaaaaaaa</ns1:Key>
<ns1:Password>aaaaaaaaaaaaaaaaaaa</ns1:Password>
</ns1:UserCredential>
</ns1:WebAuthenticationDetail>
<ns1:ClientDetail>
<ns1:AccountNumber>11111111</ns1:AccountNumber>
<ns1:MeterNumber>88888888</ns1:MeterNumber>
</ns1:ClientDetail>
<ns1:TransactionDetail>
<ns1:CustomerTransactionId>1</ns1:CustomerTransactionId>
</ns1:TransactionDetail>
<ns1:Version>
<ns1:ServiceId>crs</ns1:ServiceId>
<ns1:Major>9</ns1:Major>
<ns1:Intermediate>0</ns1:Intermediate>
<ns1:Minor>0</ns1:Minor>
</ns1:Version>
<ns1:ReturnTransitAndCommit>true</ns1:ReturnTransitAndCommit>
<ns1:RequestedShipment>
<ns1:ShipTimestamp>2013-08-06T12:39:26-04:00</ns1:ShipTimestamp>
<ns1:DropoffType>REGULAR_PICKUP</ns1:DropoffType>
<ns1:Shipper>
<ns1:AccountNumber>11111111</ns1:AccountNumber>
<ns1:Address>
<ns1:StreetLines>24 Seaview Blvd</ns1:StreetLines>
<ns1:City>Port Washington</ns1:City>
<ns1:StateOrProvinceCode>NY</ns1:StateOrProvinceCode>
<ns1:PostalCode>11050</ns1:PostalCode>
<ns1:CountryCode>US</ns1:CountryCode>
</ns1:Address>
</ns1:Shipper>
<ns1:Recipient>
<ns1:Address>
<ns1:StreetLines>1234 Fifth Street</ns1:StreetLines>
<ns1:City>Sixton</ns1:City>
<ns1:StateOrProvinceCode>AR</ns1:StateOrProvinceCode>
<ns1:PostalCode>72712</ns1:PostalCode>
<ns1:CountryCode>US</ns1:CountryCode>
</ns1:Address>
</ns1:Recipient>
<ns1:ShippingChargesPayment>
<ns1:Payor>
<ns1:AccountNumber>11111111</ns1:AccountNumber>
<ns1:CountryCode>US</ns1:CountryCode>
</ns1:Payor>
</ns1:ShippingChargesPayment>
<ns1:RateRequestTypes>ACCOUNT</ns1:RateRequestTypes>
<ns1:PackageCount>1</ns1:PackageCount>
<ns1:PackageDetail>INDIVIDUAL_PACKAGES</ns1:PackageDetail>
<ns1:RequestedPackageLineItems>
<ns1:Weight>
<ns1:Units>LB</ns1:Units>
<ns1:Value>14</ns1:Value>
</ns1:Weight>
<ns1:Dimensions>
<ns1:Length>20</ns1:Length>
<ns1:Width>20</ns1:Width>
<ns1:Height>9</ns1:Height>
<ns1:Units>IN</ns1:Units>
</ns1:Dimensions>
</ns1:RequestedPackageLineItems>
</ns1:RequestedShipment>
</ns1:RateRequest>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
I'm trying to get out values like the CountryCode, PostalCode Weight->Value and all of the Dimensions but the namespaces are confusing me. Any time I parse it, and look in the debugger all I see for any given variable is {SimpleXMLElement} [0] yet some will show output with ->asXML() but most of my attempts to access data either error out, return false, or return another {SimpleXMLElement} [0]. I just want the string/value for these nodes!
The following for example, outputs absolutely nothing:
$fReq = simplexml_load_string($xmlRequest);
$fReq->registerXPathNamespace('ns1', 'http://fedex.com/ws/rate/v9');
$ns = $fReq->getNameSpaces(true);
$rr = $fReq->children($ns['ns1']);
echo $rr->asXML()."\n";
I prefer using XMLReader: http://us3.php.net/manual/en/class.xmlreader.php
This is a example form PHP with small modification for match your requirements:
function xmlParse($content,$wrapperName,$callback,$limit=NULL){
$xml = new XMLReader();
$xml->xml($content);
$n=0;
$x=0;
while($xml->read()){
if($xml->nodeType==XMLReader::ELEMENT && $xml->name == $wrapperName){
while($xml->read() && $xml->name != $wrapperName){
if($xml->nodeType==XMLReader::ELEMENT){
$name = $xml->name;
$xml->read();
$value = $xml->value;
if(preg_match("/[^\s]/",$value)){
$subarray[$name] = $value;
}
}
}
if($limit==NULL || $x<$limit){
if($callback($subarray)){
$x++;
}
unset($subarray);
}
$n++;
}
}
$xml->close();
}
xmlParse($test,'SOAP-ENV:Envelope','callback');
function callback($array){
var_dump($array);
}
Just execute this with you XML and will return
Array
(
[ns1:Key] => aaaaaaaaaaa
[ns1:Password] => aaaaaaaaaaaaaaaaaaa
[ns1:AccountNumber] => 11111111
[ns1:MeterNumber] => 88888888
[ns1:CustomerTransactionId] => 1
[ns1:ServiceId] => crs
[ns1:Major] => 9
[ns1:Intermediate] => 0
[ns1:Minor] => 0
[ns1:ReturnTransitAndCommit] => true
[ns1:ShipTimestamp] => 2013-08-06T12:39:26-04:00
[ns1:DropoffType] => REGULAR_PICKUP
[ns1:StreetLines] => 1234 Fifth Street
[ns1:City] => Sixton
[ns1:StateOrProvinceCode] => AR
[ns1:PostalCode] => 72712
[ns1:CountryCode] => US
[ns1:RateRequestTypes] => ACCOUNT
[ns1:PackageCount] => 1
[ns1:PackageDetail] => INDIVIDUAL_PACKAGES
[ns1:Units] => IN
[ns1:Value] => 14
[ns1:Length] => 20
[ns1:Width] => 20
[ns1:Height] => 9
)
Regards
You don't need to call registerXPathNamespace unless you're using XPath. You do, however, need to traverse through the SOAP Body element, which means you need to think about two namespaces, not just one.
It's also a good idea not to rely on namespace prefixes like ns1 staying the same in the future; the part that's guaranteed is the actual URI in the xmlns attribute. One way to make this more readable is to define constants for the XML namespaces used in your application, and pass those to the ->children() and ->attributes() methods when necessary.
Note also that ->children() "selects" a namespace until further notice, so once you've selected the Fedex namespace and traversed to the RateRequest node, you can just access elements as though namespaces weren't an issue (since everything below that in this document is in that same namespace).
Here's a completed example showing how this might look (see a live demo here).
// Give your own aliases to namespaces, don't rely on the XML always having the same ones
define('NS_SOAP', 'http://schemas.xmlsoap.org/soap/envelope/');
define('NS_FEDEX_RATE', 'http://fedex.com/ws/rate/v9');
// Parse the XML
$sx = simplexml_load_string($xml_string);
// $sx now represents the <SOAP-ENV:Envelope> element
// Traverse through the SOAP Body
$sx_soap_body = $sx->children(NS_SOAP)->Body;
// Now "switch" to the Fedex namespace, and start with the RateRequest node
$sx_rate_request = $sx_soap_body->children(NS_FEDEX_RATE)->RateRequest;
// Now traverse as normal, e.g. to the Recipient's CountryCode
// (the string cast isn't necessary for echo, but is a good habit to get into)
echo (string)$sx_rate_request->RequestedShipment->Recipient->Address->CountryCode;
I'm having trouble accessing variable from an object. The object is coming from an API feed and a var_dump looks like this:
object(stdClass)#2 (1) {
["GetBookingsResult"]=>
string(189227) "<Bookings>
<Data>
<BookingDate>2012-01-06T00:00:00-06:00</BookingDate>
<StartBookingDate>2012-01-06T00:00:00-06:00</StartBookingDate>
<RoomDescription>Dorm A</RoomDescription>
<TimeEventStart>2012-01-06T15:00:00-06:00</TimeEventStart>
<TimeEventEnd>2012-01-07T00:00:00-06:00</TimeEventEnd>
<GroupName>Family Retreat</GroupName>
<EventName>Family Retreat</EventName>
<SetupTypeDescription>(none)</SetupTypeDescription>
<SetupCount>27</SetupCount>
<ReservationID>1222</ReservationID>
<EventCoordinator />
<GroupID>12</GroupID>
<VIP xml:space="preserve"> </VIP>
<VIPEvent>false</VIPEvent>
<ClosedAllDay>false</ClosedAllDay>
<OpenTime>1900-01-01T00:00:00-06:00</OpenTime>
<CloseTime>1900-01-01T00:00:00-06:00</CloseTime>
<GroupTypeDescription>Religious - Conference</GroupTypeDescription>
<EventTypeDescription>Retreat</EventTypeDescription>
<Contact>Phyllis 0000000000</Contact>
<AltContact />
<BookingID>29512</BookingID>
<TimeBookingStart>2012-01-06T15:00:00-06:00</TimeBookingStart>
<TimeBookingEnd>2012-01-07T00:00:00-06:00</TimeBookingEnd>
<GMTStartTime>2012-01-06T15:00:00-06:00</GMTStartTime>
<GMTEndTime>2012-01-07T00:00:00-06:00</GMTEndTime>
<BuildingCode>Asb</BuildingCode>
<Building>Dormitory</Building>
<RoomCode>ASB A</RoomCode>
<Room>Dorm A</Room>
<RoomID>181</RoomID>
<BuildingID>20</BuildingID>
<StatusID>1</StatusID>
<StatusTypeID>-14</StatusTypeID>
<EventTypeID>1</EventTypeID>
<GroupTypeID>1</GroupTypeID>
<DateAdded>2011-01-09T08:25:02.72-06:00</DateAdded>
<AddedBy>B Jordan</AddedBy>
<DateChanged>2012-01-08T08:34:23.2-06:00</DateChanged>
<ChangedBy>J Smith</ChangedBy>
</Data>
<Data>
<BookingDate>2012-01-06T00:00:00-06:00</BookingDate>
<StartBookingDate>2012-01-06T00:00:00-06:00</StartBookingDate>
<RoomDescription>Dorm A1</RoomDescription>
<TimeEventStart>2012-01-06T15:00:00-06:00</TimeEventStart>
<TimeEventEnd>2012-01-07T00:00:00-06:00</TimeEventEnd>
<GroupName>Family Retreat</GroupName>
<EventName>Family Retreat</EventName>
<SetupTypeDescription>(none)</SetupTypeDescription>
<SetupCount>27</SetupCount>
<ReservationID>1222</ReservationID>
<EventCoordinator />
<GroupID>12</GroupID>
<VIP xml:space="preserve"> </VIP>
<VIPEvent>false</VIPEvent>
<ClosedAllDay>false</ClosedAllDay>
<OpenTime>1900-01-01T00:00:00-06:00</OpenTime>
<CloseTime>1900-01-01T00:00:00-06:00</CloseTime>
<GroupTypeDescription>Religious - Conference</GroupTypeDescription>
<EventTypeDescription>Retreat</EventTypeDescription>
<Contact>Phyllis 0000000000</Contact>
<AltContact />
<BookingID>29512</BookingID>
<TimeBookingStart>2012-01-06T15:00:00-06:00</TimeBookingStart>
<TimeBookingEnd>2012-01-07T00:00:00-06:00</TimeBookingEnd>
<GMTStartTime>2012-01-06T15:00:00-06:00</GMTStartTime>
<GMTEndTime>2012-01-07T00:00:00-06:00</GMTEndTime>
<BuildingCode>Asb</BuildingCode>
<Building>Dormitory</Building>
<RoomCode>Asb A1</RoomCode>
<Room>Dorm A1</Room>
<RoomID>7</RoomID>
<BuildingID>20</BuildingID>
<StatusID>1</StatusID>
<StatusTypeID>-14</StatusTypeID>
<EventTypeID>1</EventTypeID>
<GroupTypeID>1</GroupTypeID>
<DateAdded>2011-01-09T08:25:02.72-06:00</DateAdded>
<AddedBy>P Jordan</AddedBy>
<DateChanged>2012-01-08T08:34:23.2-06:00</DateChanged>
<ChangedBy>J Smith</ChangedBy>
</Data>
</Bookings>"
}
I want to be able to reorder the info that comes back into an array so that I can group the events by date and then order them by EventName. Below is my code:
$xml = simplexml_load_string($result->GetBookingsResult);
$list='';
foreach($xml as $event){
$st_date = lvmDateFormat($event->TimeBookingStart,'name');//function reformats date
$en_date = lvmDateFormat($event->TimeBookingEnd,'name');
$name = lvmDateFormat($event->TimeBookingStart,'cal');
$ename = $event->EventName;
$events[lvmDateFormat($event->TimeBookingStart,'name')][$st_date] = array(
'EventName' => $ename
,'Date' => $name
,'TimeEventStart' => $st_date
,'TimeEventEnd' => $en_date
);
}
If I echo out $event->EventName; it looks fine, but when I try to add it to an array it comes back like this:
[EventName] => SimpleXMLElement Object
(
[0] => UMW Training Event
)
What am I doing wrong here?
Ta
When you echo an object, it is converted to a string. So it will appear (because SimpleXMLElement defines a __toString() method internally) like you want it to - but the type of the $event variable is still an object of type SimpleXMLElement.
You can easily store it as a string in the array, if you cast it to a string. Try changing this line:
$ename = $event->EventName;
...to this:
$ename = (string) $event->EventName;