Reading XML with PHP - Attribute Issue - php

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>

Related

simplexml_load_string() expects parameter 1 to be string when parse this Soap xml

I tried the solutions of How to parse this SOAP XML response with PHP simplexml_load_string?, but it doesn't work.
Maybe someone have an idea to how to parse this Soap XML result, you find the soap.xml and result and the test
Soap.xml
<?xml version="1.0" encoding="UTF-8"?>
<wsdl:definitions xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" ...>
<wsdl:documentation>soapExemple</wsdl:documentation>
<wsdl:types>
<xs:schema attributeFormDefault="qualified" elementFormDefault="qualified" targetNamespace="http://.../xsd">
...
Output:
<?php
ini_set("soap.wsdl_cache_enabled", "0");
const USER = "userHere";
const PASSWORD = "passHere";
$credentials = array('login' => USER, 'password' => PASSWORD);
$options = array("trace" => 1, "exception" => 0, 'encoding' => 'UTF-8');
$url = "pass/to/wsdl.xml";
$soap = new SoapClient($url, $credentials);
var_dump($soap);
try {
$result = $soap->__soapCall("reclis_XML", array("parameters"=>array("args0"=>array("METHODHERE" => "01"))));
var_dump($result);
} catch (SoapFault $exception) {
\Zend_Debug::dump( 'Exception Thrown: '.$exception->faultstring);
}
?>
Result:
object(stdClass)#6591 (1) {
["return"] => string(39171) "<?xml version="1.0" encoding="UTF-8"?>
<RECLIS>
<RESULT>KO</RESULT>
<REAL>0</REAL>
<RUS>
<REAL>0</REAL>
<CUSTOMER>
<CLEMAJ></CLEMAJ>
<NAME></NAME>
<LASTNALE>0</LASTNALE>
<PHONE>0</PHONE>
<AD></AD>
<ADDRESS1></ADDRESS1>
<ADDRESS2></ADDRESS2>
<CITY></CITY>
<CODE></CODE>
<PRICE>0</PRICE>
</CUSTOMER>
<CUSTOMER>
<CLEMAJ></CLEMAJ>
<NAME></NAME>
<LASTNALE>0</LASTNALE>
<PHONE>0</PHONE>
<AD></AD>
<ADDRESS1></ADDRESS1>
<ADDRESS2></ADDRESS2>
<CITY></CITY>
<CODE></CODE>
<PRICE>0</PRICE>
</CUSTOMER>
<CUSTOMER>
<CLEMAJ></CLEMAJ>
<NAME></NAME>
<LASTNALE>0</LASTNALE>
<PHONE>0</PHONE>
<AD></AD>
<ADDRESS1></ADDRESS1>
<ADDRESS2></ADDRESS2>
<CITY></CITY>
<CODE></CODE>
<PRICE>0</PRICE>
</CUSTOMER>
...
</RUS>
</RECLIS>
"
}
I tried this but it doesn't work:
$xml=simplexml_load_string($myXMLData) or die("Error: Cannot create object");
print_r($xml);
Have you an idea or another solution to get my xml result as an array
You have to get the string by accessing the return property
Try using:
$xml=simplexml_load_string($myXMLData->return) or die("Error: Cannot create object");
print_r($xml);

Reading XML with PHP

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);

Parse KML file with PHP

Is there a way to parse google maps *.kml file with simple_xml_load_file("*.kml") ?
I need to save in my database name and coordinates of each polygons registered in my KML file.
On my PHP script, simple_xml_load_file("*.kml") return false, so I can't read it.
<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2" xmlns:gx="http://www.google.com/kml/ext/2.2" xmlns:kml="http://www.opengis.net/kml/2.2" xmlns:atom="http://www.w3.org/2005/Atom">
<Document>
<Schema>
...
</Schema>
<Style id="FEATURES">
...
</Style>
<Folder>
<Placemark>
<name>
name
</name>
<Polygon>
<LinearRing>
<coordinates>
coordinates
</coordinates>
</LinearRing>
</Polygon>
</Placemark>
<Placemark>
...
</Placemark>
</Folder>
</Document>
</kml>
I need "name" and "coordinates" values for each "Placemark".
The xml structure is exactly that xml you sent:
For example:
<Document>
<Placemark>
<name>356HH</name>
<description>
</description>
<Polygon><outerBoundaryIs><LinearRing><coordinates>some cordinates here</coordinates></LinearRing></innerBoundaryIs></Polygon>
<Style><LineStyle><color>ff0000ff</color></LineStyle> <PolyStyle><fill>0</fill></PolyStyle></Style>
</Placemark>
<Placemark>
</document>
And it's my php code:
<?php
$completeurl = "2.xml";
$xml = simplexml_load_file($completeurl);
$placemarks = $xml->Document->Placemark;
$con=mysqli_connect("localhost","root","","j3");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query = '';
$run='';
for ($i = 0; $i < sizeof($placemarks); $i++) {
$coordinates = $placemarks[$i]->name;
$cor_d = explode(' ', $placemarks[$i]->Polygon->outerBoundaryIs->LinearRing->coordinates);
$qtmp=array();
foreach($cor_d as $value){
$tmp = explode(',',$value);
$ttmp=$tmp[1];
$tmp[1]=$tmp[0];
$tmp[0]=$ttmp;
$qtmp[]= '(' . $tmp[0] . ',' .$tmp[1].')';
}
$cor_d = json_encode($qtmp);
$query .='\''.$coordinates.'\', \''.$cor_d.'\'';
$run .="INSERT INTO jos_rpl_addon_zipinfo (name, boundary) VALUES (".$query." );";
//echo $run;
//break;
}
mysqli_query($con,$run);
//echo $run;
mysqli_close($con);
?>
The first line:
<?xml version="1.0" encoding="UTF-8"?>
Tells PHP that this is a document encoded in UTF-8, but your error says it is not encoded as UTF-8. Is this a doc you created with a text editor? If so, you can usually use your editor to save it out in UTF-8. Or you can probably use PHP to detect the encoding and change that first line.
If the XML strucutre is as what you have posted, you can try :-
$xml = simplexml_load_file(...);
$childs = $xml->Document->Folder->children();
foreach ($childs as $child)
{
// child object is same as -> Placemark
}
Example :-
SimpleXMLElement Object
(
[name] =>
name
[Polygon] => SimpleXMLElement Object
(
[LinearRing] => SimpleXMLElement Object
(
[coordinates] =>
coordinates
)
)
)

How to get the value of an xml sub element using DOMDocument methods?

I am new to PHP and XML.
Can somebody tell me how can I get the values of a sub element or child node of a an xml element?
index.php
$domdoc = new DOMDocument();
$domdoc->load('actionstars.xml');
foreach ($domdoc->getElementsByTagName("actionstar") as $star) {
echo $star->item(0)->nodeValue; // displays the <id> element
echo $star->item(1)->nodeValue; // displays the <name> element
echo "<br />";
}
actionstars.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<actionstars>
<actionstar>
<id>1</id>
<name>Jean Claude Van Damme</name>
</actionstar>
<actionstar>
<id>2</id>
<name>Scott Adkins</name>
</actionstar>
<actionstar>
<id>3</id>
<name>Dolph Ludgren</name>
</actionstar>
<actionstar>
<id>4</id>
<name>Michael Jai White</name>
</actionstar>
<actionstar>
<id>5</id>
<name>Michael Worth</name>
</actionstar>
</actionstars>
Pls help...
If you can guarantee their order, you can use childNodes and the offset, otherwise...
$domdoc = new DOMDocument();
$domdoc->load('actionstars.xml');
foreach ($domdoc->getElementsByTagName("actionstar") as $star) {
echo $shit->getElementsByTagName('id')->item(0)->nodeValue; // displays the <id> element
echo $shit->getElementsByTagName('name')->item(0)->nodeValue; // displays the <name> element
echo "<br />";
}

not able to get any results or printout while fetching attribute from xml node using dom object in php

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!

Categories