PHP - Wrong date format - php

I am trying to communicate with a SOAP server and I am sending data to server however it is rejecting the date format that I am using. I have literally tried everything for the last two days and as far as I am seeing the format is correct. This is the code I am using to generate the date. I have read over similar questions but I cant seem to find an answer in any of them.
$_dateTo=date('Y-m-d');
Output
2015-01-28
This is the error that it generates.
SoapFault Object ( [message:protected] => Date to is in wrong format, should be: 'YYYY-MM-DD' [string:Exception:private]
This is the XML
<message name="webrequestRequest">
<part name="studentId" type="xsd:integer"/>
<part name="type" type="xsd:string"/>
<part name="dateFrom" type="xsd:date"/>
<part name="dateTo" type="xsd:date"/>
<part name="description" type="xsd:string"/>
<part name="extraField1" type="xsd:string"/>
<part name="extraField2" type="xsd:string"/>
<part name="extraField3" type="xsd:string"/>
</message>

Try the following and see if it gives you any errors
$dateFrom = new DateTime();
$dateTo = new DateTime();
$writer = new XMLWriter();
$writer->openMemory();
$writer->startDocument('1.0', 'UTF-8');
$writer->startElement('message');
$writer->startElement('part');
$writer->writeAttribute('name', 'studentId');
$writer->writeAttribute('type', 'xsd:integer');
$writer->Text();
$writer->endElement($studentId);
$writer->startElement('part');
$writer->writeAttribute('name', 'type');
$writer->writeAttribute('type', 'xsd:string');
$writer->Text($type);
$writer->endElement();
$writer->startElement('part');
$writer->writeAttribute('name', 'dateFrom');
$writer->writeAttribute('type', 'xsd:date');
$writer->Text($dateFrom->format('Y-m-d'));
$writer->endElement();
$writer->startElement('part');
$writer->writeAttribute('name', 'dateTo');
$writer->writeAttribute('type', 'xsd:date');
$writer->Text($dateTo->format('Y-m-d'));
$writer->endElement();
$writer->startElement('part');
$writer->writeAttribute('name', 'description');
$writer->writeAttribute('type', 'xsd:string');
$writer->Text($description);
$writer->endElement();
$writer->startElement('part');
$writer->writeAttribute('name', 'extraField1');
$writer->writeAttribute('type', 'xsd:string');
$writer->Text($extraField1);
$writer->endElement();
$writer->startElement('part');
$writer->writeAttribute('name', 'extraField2');
$writer->writeAttribute('type', 'xsd:string');
$writer->Text($extraField2);
$writer->endElement();
$writer->startElement('part');
$writer->writeAttribute('name', 'extraField3');
$writer->writeAttribute('type', 'xsd:string');
$writer->Text($extraField3);
$writer->endElement();
$writer->endElement(); // /message
$writer->endDocument();
$message = $writer->outputMemory(true);
Don't forget to set your values first.

Related

How can I find an xml string using php in this case?

I want my php-script to download files from a specific link based on xml id's. I want it to ignore the rest of the xml-code, I want it to just look at the first id of every lib.
My xml looks like this:
**
<lib id="ITEM_I_WANT_TO_DOWNLOAD_1" revision="0000">
<part id="0000" type="ch"/>
<part id="0000" type="ls"/>
<part id="0000" type="rs"/>
<part id="0000" type="ch"/>
</lib>
<lib id="ITEM_I_WANT_TO_DOWNLOAD_2" revision="0000">
<part id="0000" type="ch"/>
<part id="0000" type="ls"/>
<part id="0000" type="rs"/>
<part id="0000" type="ch"/>
</lib>
**
My current PHP-script looks like this:
if (!defined('STDIN'))
{
echo 'Please run it as a cmd ({path to your php}/php.exe {path to badges.php} -f)';
exit;
}
define('BASE', 'https://randomtarget.com/');
$figuremap = get_remote_data('https://random/xmlfile-needed.xml/');
if (!file_exists('C:/outputfolder/')) {
mkdir('C:/outputfolder/', 0777, true);
echo "\n --------------> Output folder has been made... \n";
sleep(3);
$fp = fopen("C:/downloaded-xmlfile.xml", "w");
fwrite($fp, $figuremap);
fclose($fp);
echo "\n --------------> XML downloaded and placed into folder \n";
sleep(3);
}
$pos = 0;
while ($pos = strpos($figuremap, '<lib id="', $pos +1))
{
$pos1 = strpos($figuremap, '"', $pos);
$rule = substr($figuremap, $pos, ($pos1 -$pos));
$rule = explode(',', $rule);
$revision = str_replace('">', '', $rule[1]);
$clothing_file = current(explode('*', str_replace('"', '', $rule[2])));
if (file_exists('C:/outputfolder/'.$clothing_file.'.swf'))
{
echo 'Clothing_file found: '.$clothing_file."\r\n";
continue;
}
echo 'Download clothing_file: '.$clothing_file.' '.$revision."\r\n";
if (!#copy(BASE.'/'.$revision.'/'.$clothing_file.'.swf', 'C:/outputfolder'.$clothing_file.'.swf'))
{
echo 'Error downloading: '.$clothing_file."\r\n";
}
}
Beside this code I wrote a get_remote_data function so that's allright. I just want the strpos to grab all the id='' items to check if the files exist on the target-site.
How can I fix it?
There are some easy ways of processing XML files, the easiest (but less flexible) is SimpleXML, the following code should replace the main processing loop...
$xml = simplexml_load_string($figuremap);
foreach ( $xml->lib as $lib ) {
$clothing_file = (string) $lib['id'];
if (file_exists('C:/outputfolder/'.$clothing_file.'.swf'))
{
echo 'Clothing_file found: '.$clothing_file."\r\n";
continue;
}
echo 'Download clothing_file: '.$clothing_file.' '.$revision."\r\n";
if (!#copy(BASE.'/'.$revision.'/'.$clothing_file.'.swf', 'C:/outputfolder'.$clothing_file.'.swf'))
{
echo 'Error downloading: '.$clothing_file."\r\n";
}
}
The start point is to load the XML you have in $figuremap into SimpleXML, then to loop over the elements. This assumes an XML structure of something like...
<lib1>
<lib id="ITEM_I_WANT_TO_DOWNLOAD_1" revision="0000">
<part id="0000a" type="ch" />
<part id="0000" type="ls" />
<part id="0000" type="rs" />
<part id="0000" type="ch" />
</lib>
<lib id="ITEM_I_WANT_TO_DOWNLOAD_2" revision="0000">
<part id="00001" type="ch" />
<part id="0000" type="ls" />
<part id="0000" type="rs" />
<part id="0000" type="ch" />
</lib>
</lib1>
The actual name of the base element doesn't matter as long as the <lib> elements are 1 level down then you can use $xml->lib to loop over them.
Your posted xml string is actually invalid. It needs to be wrapped in a parent element to be repaired. I'm not sure if you are posting your exact xml string or just a section of it.
$xml = '<lib id="ITEM_I_WANT_TO_DOWNLOAD_1" revision="0000">
<part id="0000" type="ch"/>
<part id="0000" type="ls"/>
<part id="0000" type="rs"/>
<part id="0000" type="ch"/>
</lib>
<lib id="ITEM_I_WANT_TO_DOWNLOAD_2" revision="0000">
<part id="0000" type="ch"/>
<part id="0000" type="ls"/>
<part id="0000" type="rs"/>
<part id="0000" type="ch"/>
</lib>';
$xml = '<mydocument>' . $xml . '</mydocument>'; // repair invalid xml
https://stackoverflow.com/q/4544272/2943403
$doc = new DOMDocument();
$doc->loadXml($xml);
$xpath = new DOMXpath($doc);
foreach ($xpath->evaluate('//lib/#id') as $attr) {
$clothing_file = $attr->value;
// perform your conditional actions ...
}
//lib/#id says search for the id attribute of all <lib> elements, anywhere in the document.

Nusoap "SOAP-ENV: Xml was empty, didn't parse" Message

I'm trying to implement a simple webservice using nusoap.
Server:
<?php
require_once "nusoaplib/nusoap.php";
class food {
public function getFood($type) {
switch ($type) {
case 'starter':
return 'Soup';
break;
case 'Main':
return 'Curry';
break;
case 'Desert':
return 'Ice Cream';
break;
default:
break;
}
}
}
$server = new soap_server();
$server->configureWSDL("foodservice", "urn:foodservice");
$server->register("food.getFood",
array("type" => "xsd:string"),
array("return" => "xsd:string"),
"urn:foodservice",
"urn:foodservice#getFood",
"rpc",
"encoded",
"Get food by type");
#$server->service($HTTP_RAW_POST_DATA);
?>
Client:
<?php
require_once "nusoaplib/nusoap.php";
$client = new nusoap_client("http://localhost/SOAPServer.php?wsdl", true);
$error = $client->getError();
if ($error) {
echo "<h2>Constructor error</h2><pre>" . $error . "</pre>";
}
$result = $client->call("food.getFood", array("type" => "Main"));
if ($client->fault) {
echo "<h2>Fault</h2><pre>";
print_r($result);
echo "</pre>";
} else {
$error = $client->getError();
if ($error) {
echo "<h2>Error</h2><pre>" . $error . "</pre>";
} else {
echo "<h2>Main</h2>";
echo $result;
}
}
// show soap request and response
echo "<h2>Request</h2>";
echo "<pre>" . htmlspecialchars($client->request, ENT_QUOTES) . "</pre>";
echo "<h2>Response</h2>";
echo "<pre>" . htmlspecialchars($client->response, ENT_QUOTES) . "</pre>";
?>
The wsdl file is generated by nusoap, which is the following:
<definitions xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:tns="urn:foodservice" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns="http://schemas.xmlsoap.org/wsdl/" targetNamespace="urn:foodservice">
<types>
<xsd:schema targetNamespace="urn:foodservice">
<xsd:import namespace="http://schemas.xmlsoap.org/soap/encoding/"/>
<xsd:import namespace="http://schemas.xmlsoap.org/wsdl/"/>
</xsd:schema>
</types>
<message name="food.getFoodRequest">
<part name="type" type="xsd:string"/>
</message>
<message name="food.getFoodResponse">
<part name="return" type="xsd:string"/>
</message>
<portType name="foodservicePortType">
<operation name="food.getFood">
<documentation>Get food by type</documentation>
<input message="tns:food.getFoodRequest"/>
<output message="tns:food.getFoodResponse"/>
</operation>
</portType>
<binding name="foodserviceBinding" type="tns:foodservicePortType">
<soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/>
<operation name="food.getFood">
<soap:operation soapAction="urn:foodservice#getFood" style="rpc"/>
<input>
<soap:body use="encoded" namespace="urn:foodservice" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
</input>
<output>
<soap:body use="encoded" namespace="urn:foodservice" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
</output>
</operation>
</binding>
<service name="foodservice">
<port name="foodservicePort" binding="tns:foodserviceBinding">
<soap:address location="http://10.152.128.39/SOAPServer.php"/>
</port>
</service>
</definitions>
When accessing both the server file and the wsdl file, they both work, but I get the error message when I try to access the client:
[faultcode] => SOAP-ENV:Client
[faultactor] =>
[faultstring] => error in msg parsing:
xml was empty, didn't parse!
[detail] =>
Any suggestions what could be the problem?
In your nusoap. Server you should change:
This:
#$server->service($HTTP_RAW_POST_DATA);
for this:
#$server->service(file_get_contents("php://input"));
You may remove the # if you want to check notices and warnings.
Some explanation from http://php.net/manual/en/ini.core.php#ini.always-populate-raw-post-data
This feature was DEPRECATED in PHP 5.6.0, and REMOVED as of PHP 7.0.0.
If set to TRUE, PHP will always populate the $HTTP_RAW_POST_DATA containing the raw POST data. Otherwise, the variable is populated only when the MIME type of the data is unrecognised.
The preferred method for accessing raw POST data is php://input, and $HTTP_RAW_POST_DATA is deprecated in PHP 5.6.0 onwards. Setting always_populate_raw_post_data to -1 will opt into the new behaviour that will be implemented in a future version of PHP, in which $HTTP_RAW_POST_DATA is never defined.
Regardless of the setting, $HTTP_RAW_POST_DATA is not available with enctype="multipart/form-data".

getting element values from an xml soap response when there is double xml tag

I HAVE THIS XML RESPONSE FROM A SOAP CALL:
<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><loginResponse xmlns="http://wws.adomain.com/"><loginResult><xs:schema id="NewDataSet" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"><xs:element name="NewDataSet" msdata:IsDataSet="true" msdata:MainDataTable="replay" msdata:UseCurrentLocale="true"><xs:complexType><xs:choice minOccurs="0" maxOccurs="unbounded"><xs:element name="replay"><xs:complexType><xs:sequence><xs:element name="code" type="xs:string" minOccurs="0" /><xs:element name="description" type="xs:string" minOccurs="0" /></xs:sequence></xs:complexType></xs:element></xs:choice></xs:complexType></xs:element></xs:schema><diffgr:diffgram xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1"><DocumentElement xmlns=""><replay diffgr:id="replay1" msdata:rowOrder="0" diffgr:hasChanges="inserted"><code>OK</code><description>
<?xml version="1.0" encoding="UTF-8"?><root><token>e6d354f2-b284569e20-b2def8f3ef4a</token><nmDealer>SAP001 NAME</nmDealer><idRegDealer>8763</idRegDealer><idRegGrupo>-1</idRegGrupo><idRegPuntoVenta>-1</idRegPuntoVenta><idRegUsuario>35350731</idRegUsuario><idRegVendedor>-1</idRegVendedor><idRegZona>-1</idRegZona><dsTpUsuario>CLIENTES</dsTpUsuario><dsPais>PRODUCCION</dsPais><idioma>EN</idioma><idRegIdioma>9</idRegIdioma><isImputar>False</isImputar><moneda>€</moneda><tpUsuario>1</tpUsuario><idRegComisionVariableDealer>-1</idRegComisionVariableDealer><permitirComisionVariableDealer>1</permitirComisionVariableDealer><firstAccess>0</firstAccess><acceptedConditions>False</acceptedConditions><idRegInsured>-1</idRegInsured><idRegAuditor>-1</idRegAuditor></root></description></replay></DocumentElement></diffgr:diffgram></loginResult></loginResponse></soap:Body></soap:Envelope>
http://prntscr.com/9cfdwk
I want to be able to get the values of element (eg token) in the second xml tag (<?xml version="1.0" encoding="UTF-8"?>) Any prompt assistance will be appreciated.
HERE IS MY CODE:
$s = new soapclientw($wsdlfile);
if (empty($proxyhost))
{
}
else{
$s->setHTTPProxy($proxyhost,$proxyport,$proxyusr,$proxypassword);
}
$result = $s->send($msg,'http://wws.domain.com/login',60);
$myXMLData = $s->responseData;
libxml_use_internal_errors(true);
$xml = simplexml_load_string($myXMLData);
if ($xml === false) {
echo "Failed loading XML: ";
foreach(libxml_get_errors() as $error) {
echo "<br>", $error->message;
}
}
else{
echo $xml->token;
}
Given your original, highly dubious xml, the following is a bit of a hack but it works..
$strxml='
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<loginResponse xmlns="http://wws.adomain.com/">
<loginResult>
<xs:schema id="NewDataSet" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xs:element name="NewDataSet" msdata:IsDataSet="true" msdata:MainDataTable="replay" msdata:UseCurrentLocale="true">
<xs:complexType>
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="replay">
<xs:complexType>
<xs:sequence>
<xs:element name="code" type="xs:string" minOccurs="0" />
<xs:element name="description" type="xs:string" minOccurs="0" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:choice>
</xs:complexType>
</xs:element>
</xs:schema>
<diffgr:diffgram xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1">
<DocumentElement xmlns="">
<replay diffgr:id="replay1" msdata:rowOrder="0" diffgr:hasChanges="inserted">
<code>OK</code>
<description>
<?xml version="1.0" encoding="UTF-8"?>
<root>
<token>e6d354f2-b284569e20-b2def8f3ef4a</token>
<nmDealer>SAP001 NAME</nmDealer>
<idRegDealer>8763</idRegDealer>
<idRegGrupo>-1</idRegGrupo>
<idRegPuntoVenta>-1</idRegPuntoVenta>
<idRegUsuario>35350731</idRegUsuario>
<idRegVendedor>-1</idRegVendedor>
<idRegZona>-1</idRegZona>
<dsTpUsuario>CLIENTES</dsTpUsuario>
<dsPais>PRODUCCION</dsPais>
<idioma>EN</idioma>
<idRegIdioma>9</idRegIdioma>
<isImputar>False</isImputar>
<moneda>€</moneda>
<tpUsuario>1</tpUsuario>
<idRegComisionVariableDealer>-1</idRegComisionVariableDealer>
<permitirComisionVariableDealer>1</permitirComisionVariableDealer>
<firstAccess>0</firstAccess>
<acceptedConditions>False</acceptedConditions>
<idRegInsured>-1</idRegInsured>
<idRegAuditor>-1</idRegAuditor>
</root>
</description>
</replay>
</DocumentElement>
</diffgr:diffgram>
</loginResult>
</loginResponse>
</soap:Body>
</soap:Envelope>';
$strxml=htmlentities( $strxml );
$search=array(
htmlentities( '<?xml version="1.0" encoding="utf-8"?>' ),
htmlentities( '<?xml version="1.0" encoding="UTF-8"?>' )
);
$strxml=html_entity_decode( str_replace( $search, '', $strxml ) );
libxml_use_internal_errors( true );
$dom = new DOMDocument('1.0','utf-8');
$dom->validateOnParse=false;
$dom->standalone=true;
$dom->preserveWhiteSpace=true;
$dom->strictErrorChecking=false;
$dom->substituteEntities=false;
$dom->recover=true;
$dom->formatOutput=false;
$dom->loadXML( $strxml );
libxml_clear_errors();
$col=$dom->getElementsByTagName('root')->item(0);
if( $col ){
foreach( $col->childNodes as $node ) echo $node->tagName.' '.$node->nodeValue.BR;
}
$dom=null;
Thanks all, I was able to figure it out myself.
Here is the code that worked for me:
$myXMLData = strip_tags($s->responseData);
$temp = explode("OK", $myXMLData);
$myXMLData = $temp[1];
$xml = new SimpleXMLElement(htmlspecialchars_decode($myXMLData));
I stripped off all the soap tags, living me with the final xml data but with a leading 'OK' which I removed by explode(). Replacing the 'OK' with an empty string would have also worked.

How can I add custom elements to the detail section of a SoapFault using PHP's SOAP library

I am building a service against Sonos' Music API (SMAPI). Sometimes I have to send back a response in the following format:
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<soap:Fault>
<faultcode>Client.NOT_LINKED_RETRY</faultcode>
<faultstring>Link Code not found retry...</faultstring>
<detail>
<ExceptionInfo>NOT_LINKED_RETRY</ExceptionInfo>
<SonosError>5</SonosError>
</detail>
</soap:Fault>
</soap:Body>
</soap:Envelope>
I am building my service using the PHP SOAP library and for the above response I tried throwing a SoapFault like this:
throw new SoapFault('Client.NOT_LINKED_RETRY', 'Link Code not found retry...');
But when I try this the response that is sent back looks like this:
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<soap:Fault>
<faultcode>Client.NOT_LINKED_RETRY</faultcode>
<faultstring>Link Code not found retry...</faultstring>
<detail>
<SonosError/>
</detail>
</soap:Fault>
</soap:Body>
</soap:Envelope>
Notice that there is no ExceptionInfo and that SonosError is empty. Is it possible to set ExceptionInfo and SonosError using SoapFault? I tried all kinds of things, but couldn't get it working, so as a work around I am doing this now:
http_response_code(500);
header("Content-type: text/xml");
$ret = '<?xml version="1.0" encoding="UTF-8"?>'."\n";
$ret .= '<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">';
$ret .= '<SOAP-ENV:Body>';
$ret .= '<SOAP-ENV:Fault>';
$ret .= '<faultcode>Client.NOT_LINKED_RETRY</faultcode>';
$ret .= '<faultstring>Link Code not found retry...</faultstring>';
$ret .= '<detail>';
$ret .= '<ExceptionInfo>NOT_LINKED_RETRY</ExceptionInfo>';
$ret .= '<SonosError>5</SonosError>';
$ret .= '</detail>';
$ret .= '</SOAP-ENV:Fault>';
$ret .= '</SOAP-ENV:Body>';
$ret .= '</SOAP-ENV:Envelope>'."\n";
echo $ret; exit;
Not sure if it's relevant but the WSDL can be found here.
Update: when I try the suggestion below like this:
$detail = new StdClass();
$detail->SonosError = 5;
$detail->ExceptionInfo = 'NOT_LINKED_RETRY';
throw new SoapFault(
'Client.NOT_LINKED_RETRY',
'Link Code not found retry...',
NULL,
$detail
);
I get:
<detail>
<customFault>
<SonosError>5</SonosError>
<ExceptionInfo>NOT_LINKED_RETRY</ExceptionInfo>
</customFault>
</detail>
This is almost what I need, except for <customFault> tag. Is there a way to get rid of it and have SonosError and ExceptionInfo in <detail> directly?
The fact that you don't see the ExceptionInfo tag is because it is not defined in the wsdl. On the other hand SonosError is defined.
First thing first, in order to fill the SonosError you have to pass the arguments.
From here you can see that the constructor has more parameters
SoapFault('code', 'string', 'actor', 'detail', 'name', 'header');
In order to pass the SonosError call it like this
$detail = new StdClass();
$detail->SonosError = 5;
throw new SoapFault('Client.NOT_LINKED_RETRY', 'Link Code not found retry...', null, $details);
As for the ExceptionInfo, the wsdl must be changed. As it is now, the details tag is represented by this sections
<wsdl:message name="customFault">
<wsdl:part name="customFault" element="tns:SonosError"/>
</wsdl:message>
<xs:element name="SonosError" type="xs:int"/>
If you change the above sections with these, you will have what you need.
<wsdl:message name="customFault">
<wsdl:part name="customFault" type="tns:customFaultType" />
</wsdl:message>
<xs:complexType name="customFaultType">
<xs:sequence>
<xs:element name="SonosError" type="xs:int"/>
<xs:element name="ExceptionInfo" type="xs:string"/>
</xs:sequence>
</xs:complexType>
And of course you add the parameter and the array becomes like this
$detail = new StdClass();
$detail->SonosError = 5;
$detail->ExceptionInfo = 'NOT_LINKED_RETRY';

read XML tag id from php

i am have the following XML file
<?xml version="1.0" encoding="iso-8859-1"?>
<Message Id="Language">German</Message>
<Message Id="LangEnglish">German</Message>
<Message Id="TopMakeHomepage">
Mache 4W Consulting Webseite zu deiner Starseite!
</Message>
<Message Id="TopLinkEmpSec">
4W Mitarbeiter
</Message>
<Message Id="TopLinkFeedback">
Feedback
</Message>
<Message Id="TopLinkSiteMap">
Site Map
</Message>
<Message Id="TopLinkContactUs">
Kontakt
</Message>
<Message Id="TopSetLangEn">
ins Englische
</Message>
<Message Id="TopSetLangDe">
ins Deutsche
</Message>
<Message Id="TopSetLangEs">
ins Spanische
</Message>
<Message Id="MenuLinks">
!~|4W Starseite|Company|Über uns|Kontakt|4W anschließen|Services|Kunden Software Entwicklung|Altsystem Neugestalltung & Umwandlung|Altsystem Dokumentation|Daten Umwandlung & Migration|Erstellen von Datenbeschreibungsverzeichnis|System- & Anwendungs Support|Projekt Management & Planunng|Personal Erweiterung|Projekt Ausgliederung|Mitarbeiter Ausbildung|Technologie|Intersystems Caché|M / MUMPS|Zusätzliche Technologien|Methodologie|Feedback|~!
</Message>
</MsgFile>
in this XML file i need to fetch the contents using the tagid . what exactly i need is when i input the 'TopMakeHomepage' i need output as 'Mache 4W Consulting Webseite zu deiner Starseite!' ...
Please help me to find out this . Thanks in advance
Use SimpleXML:
$xml = simplexml_load_file($grabUrl);
foreach ($xml->Message as $message) {
echo $message->attributes()->Id.'<br />';
}
Or use XMLReader, with which you can miss memory leaks when processing large XMLs.
$xml = new XMLReader;
$xml->open($grabUrl);
while ($xml->read()) {
if ($xml->nodeType === XMLReader::ELEMENT && $xml->name == 'Message')
echo $xml->getAttribute('Id');
}
With the DOM extension it should be something like this:
$dom = new DOMDocument;
$dom->validateOnParse = TRUE;
$dom->loadXML($xmlString); // or use ->load('file.xml')
$node = $dom->getElementById('foo');
echo $node->nodeValue;
See the manual on
DOMDocument::getElementById — Searches for an element with a certain id
If it doesn't work with getElementById (which usually only happens if the DTD doesn't know the id attribute), you can still use XPath to do the query:
$xpath = new DOMXPath($dom);
$nodes = $xpath->query('//Message[#id = "foo"]');
foreach($nodes as $node) {
echo $node->nodeValue;
}
Unlike getElementById, an XPath query always returns a DOMNodeList. It will be empty if the query didn't find any nodes.
If the ID is a real XML ID, you can also use the id() function in XPath
$xpath = new DOMXPath($dom);
$nodes = $xpath->query('id("foo")');
foreach($nodes as $node) {
echo $node->nodeValue;
}
See Simplify PHP DOM XML parsing - how? for more details on XML IDs.
For SimpleXML this should do the trick:
$xml = simplexml_load_file($xmlFileLoc);
foreach ($xml->Message as $msg)
{
echo $msg['Id'];
}

Categories