I am testing out some things with reading XML using PHP. The below is a sample of the XML File:
<?xml version="1.0" encoding="UTF-8" ?>
<BroadcastData creationDate="20140326085217">
<ScheduleData>
<ChannelPeriod beginTime="20140326090000" endTime="20140402044500">
<ChannelId>Rai Uno</ChannelId>
<Event beginTime="20140326090000" duration="1800">
<EventId>260852180006</EventId>
<EventType>P</EventType>
<EpgProduction>
<EpgText language="eng">
<Name>Unomattina storie vere</Name>
</EpgText>
</EpgProduction>
</Event>
<Event beginTime="20140326093000" duration="1500">
<EventId>260852180007</EventId>
<EventType>P</EventType>
<EpgProduction>
<EpgText language="eng">
<Name>Unomattina Verde</Name>
</EpgText>
</EpgProduction>
</Event>
This is the PHP Script I built, however notthing is showing on when I run the PHP file.
<?php
$completeurl ="test.xml";
$xml = simplexml_load_file($completeurl);
$info = $xml->BroadcastData->ScheduleData->ChannelPeriod->ChannelId;
for ($i = 0; $i++) {
$begintime = $info[$i]->Event->attributes()->beginTime;
echo "<p>Channel: ".$info."<br/>"."Begin Time: ".$begintime."</p>";
}
?>
Many thanks for your help guys !
You should iterate over each channel period rather than channel id (which is a sub element anyway):
$doc = simplexml_load_file($completeurl);
foreach ($doc->ScheduleData->ChannelPeriod as $channelPeriod) {
$channelId = (string)$channelPeriod->ChannelId;
foreach ($channelPeriod->Event as $event) {
$beginTime = $event['beginTime'];
printf('<p>Channel: %s<br />Begin Time: %s</p>', $channelId, $beginTime);
}
}
use following function to convert the xml string into array
json_decode(json_encode((array)simplexml_load_string($sXML)),1);
Related
I have following XML (source.xml):
<SHOP>
<SHOPITEM>
<ITEM_ID>3664</ITEM_ID>
<PRODUCT>Product n.1</PRODUCT>
<PRODUCT_NAME>Product n.1</PRODUCT_NAME>
<VARIANT_NAME/>
<MANUFACTURER>Jeffrey</MANUFACTURER>
<CODE>ABC123</CODE>
<EAN>123456789</EAN>
<DESCRIPTION>
Maybe later...
</DESCRIPTION>
<DESCRIPTION_HTML/>
<CATEGORIES>
<CATEGORY id="1" parent_id="0">ABx</CATEGORY>
</CATEGORIES>
</SHOPITEM>
<SHOPITEM>
...etc
And following code:
$xml = simplexml_load_file("source.xml", NULL, LIBXML_NOCDATA);
foreach ($xml->shopitem as $shopitem) {
echo $shopitem->item_id;
}
Unfortunately, it doesn't work. Even if I put echo 'a'; into foreach cycle, nothing appears. XML is valid. Tried var_dump($xml) and the XML looks to be loaded correctly. What is wrong? Thank you.
$xml = simplexml_load_file("source.xml", NULL, LIBXML_NOCDATA);
foreach ($xml->SHOPITEM as $shopitem) {
echo $shopitem->ITEM_ID;
}
I have a log file whose content is like the one below
2016-04-07 19:37:48 <order merchant="asc" affiliate="" id="UM9E-C01101518" date="1443723720" event_id="1" ref="GDVJT" alias="asc">
<event type="sale" date="2015-10-01 18:22:00" status_code="SA">
<sale amount="61.45" amount_usd="43.94" method="VISA" currency="CAD" processor="visa"/>
<tax amount="7.37" amount_usd="5.28" currency="CAD"/>
<payout amount="39.89" currency="USD"/>
</event>
<customer>
<name>Frank</name>
<email>frank#gmail.com</email>
<address/>
<region>BC</region>
<country>IN</country>
<zip_postal>V8V1J9</zip_postal>
<phone_number>1231231234</phone_number>
<language>EN</language>
<ip>209.13.233.227</ip>
<currency>CAD</currency>
</customer>
I am trying to extract the value of name and email from this log file.
I am using the below code:
$handle = fopen('vendorOrder.log','r') or die ('File opening failed');
while (!feof($handle)) {
$dd = fgets($handle);
$str = htmlentities($dd, ENT_XHTML);
if(preg_match("/<name>(.*)<\/name>/",$str)){
$txt = getTextBetweenTags($str, "name");
echo $txt;
}
}
fclose($handle);
function getTextBetweenTags($string, $tagname) {
$pattern = "/<$tagname>(.*)<\/$tagname>/";
preg_match($pattern, $string, $matches);
return $matches[0];
}
But it is never matching the name tag and I am not able to get the value between the tags.
I need the output as Frank.
Can someone let me know whats wrong in the code
Use simplexml_load_file() php function.
Example:
$xml=simplexml_load_file("vendorOrder.log") or die("Error: Cannot create object");
And get this value with $xml->customer->name
Maybe your XML are crashed. Try this format.
<order merchant="asc" affiliate="" id="UM9E-C01101518" date="1443723720" event_id="1" ref="GDVJT" alias="asc">
<event type="sale" date="2015-10-01 18:22:00" status_code="SA">
<sale amount="61.45" amount_usd="43.94" method="VISA" currency="CAD" processor="visa"/>
<tax amount="7.37" amount_usd="5.28" currency="CAD"/>
<payout amount="39.89" currency="USD"/>
</event>
<customer>
<datetime>2016-04-07 19:37:48</datetime>
<name>Frank</name>
<email>frank#gmail.com</email>
<address/>
<region>BC</region>
<country>IN</country>
<zip_postal>V8V1J9</zip_postal>
<phone_number>1231231234</phone_number>
<language>EN</language>
<ip>209.13.233.227</ip>
<currency>CAD</currency>
</customer>
</order>
Yup as stated use simplexml_load_file($url) ; to parse xml.
you can find examples here : http://www.w3schools.com/php/php_xml_simplexml_get.asp
Make a correction in original string with something like this:
<?php
$xml_file = 'vendorOrder.log';
$xml_content = file_get_contents( $xml_file );
$xml_content .= "\n</order>";
$xml_content = substr( $xml_content, 20 );
var_dump($xml_content);
$xml=simplexml_load_string($xml_content) or die("Error: Cannot create object");
echo $xml->customer->name;
I can read XML files or strings but not the next:
$str = <<<XML
<Output xmlns="nice.uniform://" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Data i:nil="true"/>
<Result xmlns:a="http://nice.uniform/CLSAPI3">
<a:ResultCode>SUCCESS</a:ResultCode>
<a:ResultMessage>OK</a:ResultMessage>
<a:ResultCodeEx>CLS_SE_SUCCESS</a:ResultCodeEx>
</Result>
<Exception i:nil="true" xmlns:a="http://schemas.datacontract.org/2004/07/System"/>
</Output>
XML;
My PHP code to read a node of XML file is:
$Output = new SimpleXMLElement($str);
echo $Output->Result->{'a:ResultCodeEx'};
Also, I've tried:
$xmlResponse = simplexml_load_file('file.xml');
foreach($xmlResponse->Result as $xmlEntry)
{
echo $xmlEntry->{'a:ResultCodeEx'};
}
//or
$blocks = $xmlResponse->xpath('//Output');
print_r($blocks);
Can you help me?
The document uses several namespaces. The element ResultCodeEx belongs to the namespace a. You can use XPath, but you need to register the namespace a before the query:
$Output = new SimpleXMLElement($str);
$Output->registerXPathNamespace ('a', 'http://nice.uniform/CLSAPI3');
$result = $Output->xpath('//a:ResultCodeEx/text()');
echo $result[0]; // CLS_SE_SUCCESS
I have the below XML sample file which I am trying to display using PHP:
<?xml version="1.0" encoding="UTF-8" ?>
<BroadcastData creationDate="20140326085217">
<ScheduleData>
<ChannelPeriod beginTime="20140326090000" endTime="20140402044500">
<ChannelId>Rai Uno</ChannelId>
<Event beginTime="20140326090000" duration="1800">
<EventId>260852180006</EventId>
<EventType>P</EventType>
<EpgProduction>
<EpgText language="eng">
<Name>Unomattina storie vere</Name>
</EpgText>
</EpgProduction>
</Event>
<Event beginTime="20140326093000" duration="1500">
<EventId>260852180007</EventId>
<EventType>P</EventType>
<EpgProduction>
<EpgText language="eng">
<Name>Unomattina Verde</Name>
</EpgText>
</EpgProduction>
</Event>
The below is the PHP code to parse the XML:
// Create connection
$con=mysqli_connect("localhost","test","test","epg");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$completeurl ='test.xml';
$doc = simplexml_load_file($completeurl);
foreach ($doc->ScheduleData->ChannelPeriod as $channelPeriod) {
$channelId = $channelPeriod->ChannelId;
foreach ($channelPeriod->Event as $event) {
$beginTime = $event->['beginTime'];
foreach ($channelPeriod->Event as $name) {
$programName = $name->EpgProduction->EpgText->Name;
printf('<p>Channel: %s<br />Begin Time: %s<br />Program Name: %s</p>', $channelId, $beginTime, $programName);
}
}
}
?>
For some reason the loop to show the attribute begin time is being shown repetitively for every name, the is a sample which I have when I execute the script:
Channel: Rai Uno
Begin Time: 260852180006
Program Name: Unomattina storie vere
Channel: Rai Uno
Begin Time: 260852180006
Program Name: Unomattina Verde
As you can see above the Begin time is repeated and not matching with the xml file.
Try like that:
foreach ( $doc->ScheduleData->ChannelPeriod as $channelPeriod )
{
$channelId = $channelPeriod->ChannelId;
foreach ( $channelPeriod->Event as $event )
{
$beginTime = $event['beginTime'];
$programName = $event->EpgProduction->EpgText->Name;
printf( '<p>Channel: %s<br />Begin Time: %s<br />Program Name: %s</p>', $channelId, $beginTime, $programName );
}
}
It outputs:
Channel: Rai Uno
Begin Time: 20140326090000
Program Name: Unomattina storie vere
Channel: Rai Uno
Begin Time: 20140326093000
Program Name: Unomattina Verde
Also, your xml should look like this:
<?xml version="1.0" encoding="UTF-8" ?>
<BroadcastData creationDate="20140326085217">
<ScheduleData>
<ChannelPeriod beginTime="20140326090000" endTime="20140402044500">
<ChannelId>Rai Uno</ChannelId>
<Event beginTime="20140326090000" duration="1800">
<EventId>260852180006</EventId>
<EventType>P</EventType>
<EpgProduction>
<EpgText language="eng">
<Name>Unomattina storie vere</Name>
</EpgText>
</EpgProduction>
</Event>
<Event beginTime="20140326093000" duration="1500">
<EventId>260852180007</EventId>
<EventType>P</EventType>
<EpgProduction>
<EpgText language="eng">
<Name>Unomattina Verde</Name>
</EpgText>
</EpgProduction>
</Event>
</ChannelPeriod>
</ScheduleData>
</BroadcastData>
here's an example of the ticketcity.xml file im using:
<Events Version="3.0" Method="GetEvents" StatusCode="0" StatusMsg="Success">
−
<Event ID="569402" Name="Hair" SeatingChart="http://www.ticketcity.com/images/seatingcharts/MARTINBECK_THEATRE_NYC.GIF" Page="http://www.ticketcity.com/theatre-tickets/broadway-tickets/hair-tickets/hair-tickets-al-hirschfeld-theatre-february-3-200pm.html" EventDateTime="02/03/2010 2:00PM">
<Performer ID="463" Name="Hair" Primary="true"/>
−
<Venue ID="961" Name="Al Hirschfeld Theatre">
<City ID="36469" Name="New York"/>
<State ID="34" Abbr="NY" Name="New York"/>
<Country ID="1" Abbr="US" Name="United States"/>
</Venue>
</Event>
−
</Events>
and the php script to fetch the data:
$ticketcity = new DOMDocument();
$ticketcity->load("ticketcity.xml");
if (empty($ticketcity))
echo "there was some kind of issue fetching the document";
else {
echo "xml loaded, beginning update<br>\n";
$events = $ticketcity->getElementsByTagName("Event");
$i=0;
foreach ($events as $event){
echo $i."<br>\n";
$eventid = $event->getAttribute('ID');
$eventname = $event->getAttribute('Name');
$eventmap = $event->getAttribute('SeatingChart');
$eventpage = $event->getAttribute('Page');
echo "$eventid, $eventname, $eventmap, $eventpage<br>\n";
$i++;
}
I have the $i there just for debugging, so that I'd have some printout at all... The problem is that I don't have anything. I get absolutely no printout from anything except "xml loaded, beginning update"
The script couldn't be any simpler, and it works fine with another XML file, the only difference between this and the other xml file is that the other file's data is stored in node values, and not attributes... I'm going crazy over this, what am I missing?
You should try to do this:
$ticketcity = new DOMDocument();
if (!$ticketcity->load("ticketcity.xml"))
echo "there was some kind of issue fetching the document";
else {
// your code...
}
$ticketcity will always contain an object of class DOMDocument but load returns false on failure:
Returns TRUE on success or FALSE on failure. If called statically, returns a DOMDocument and issues E_STRICT warning.
I just ran this on my local machine, and it works fine:
<?
$xml = '<Events Version="3.0" Method="GetEvents" StatusCode="0" StatusMsg="Success">
−
<Event ID="569402" Name="Hair" SeatingChart="http://www.ticketcity.com/images/seatingcharts/MARTINBECK_THEATRE_NYC.GIF" Page="http://www.ticketcity.com/theatre-tickets/broadway-tickets/hair-tickets/hair-tickets-al-hirschfeld-theatre-february-3-200pm.html" EventDateTime="02/03/2010 2:00PM">
<Performer ID="463" Name="Hair" Primary="true"/>
−
<Venue ID="961" Name="Al Hirschfeld Theatre">
<City ID="36469" Name="New York"/>
<State ID="34" Abbr="NY" Name="New York"/>
<Country ID="1" Abbr="US" Name="United States"/>
</Venue>
</Event>
−
</Events>
';
$ticketcity = new DOMDocument();
$ticketcity->loadXML($xml);
if (empty($ticketcity))
echo "there was some kind of issue fetching the document";
else {
echo "xml loaded, beginning update<br>\n";
$events = $ticketcity->getElementsByTagName("Event");
$i=0;
foreach ($events as $event){
echo $i."<br>\n";
$eventid = $event->getAttribute('ID');
$eventname = $event->getAttribute('Name');
$eventmap = $event->getAttribute('SeatingChart');
$eventpage = $event->getAttribute('Page');
echo "$eventid, $eventname, $eventmap, $eventpage<br>\n";
$i++;
}
}
I suspect the file is missing, because DOMDocument will still hit the else clause even if it couldn't load the document. $ticketcity would not be empty!