Error while Getting data from an xml file - php

I have written the following code to understand how php can be used to get and write data to xml files:
<?php
if (file_exists('/requests.xml')) {
$xml = simplexml_load_file('requests.xml');
foreach($xml->data->requests->request as $req)
{
print "Loop entered";
print $req->ip;
print $req->timelast;
}
}
?>
The xml file requests.xml follows:
<?xml version="1.0" encoding="utf-8"?>
<data>
<requests>
<request>
<ip>6.6.6.6</ip>
<timelast>2014-05-30 11:38:23</timelast>
</request>
</requests>
</data>
The problem is that when the script is run, it does not display anything in the browser. In fact it does not enter the loop.
I'm definitely missing something basic.

$xml will take your default node auto so no need to fetch result with data try
foreach($xml->requests->request as $req)
also change
if (file_exists('/requests.xml')) {
to
if (file_exists('requests.xml')) { // if same dir
i have tried like:-
$xml ='<?xml version="1.0" encoding="utf-8"?>
<data>
<requests>
<request>
<ip>6.6.6.6</ip>
<timelast>2014-05-30 11:38:23</timelast>
</request>
</requests>
</data>';
$xml = simplexml_load_string($xml);
foreach($xml->requests->request as $req)
{
print "Loop entered";
print $req->ip;
print $req->timelast;
}
output :- Loop entered6.6.6.62014-05-30 11:38:23

<?php
try
{
$feed = new SimpleXMLElement('requests.xml', null, true);
}
catch(Exception $e)
{
echo $e->getMessage();
exit;
}
foreach($feed->member as $property)
{
echo $property->id;
echo $property->lastName;
}
?>
XML :
1
MSDWEr

Related

PHP updating xml CDATA fields with DOMdocument

I have the following XML data:
<?xml version="1.0" encoding="utf-8"?>
<source>
<publisher>some-data</publisher>
<publisherurl>some-data</publisherurl>
<lastBuildDate>a-date</lastBuildDate>
<element>
<sub-element><![CDATA[some-data]]></sub-element>
</element>
</source>
I'm trying to use PHP's built in DOMdocument parser to update the text inside sub-element.
I've tried:
$dom=new DOMDocument();
$dom->load("document.xml");
$ele=$root->getElementsByTagName('element');
foreach ($ele as $e) {
$e->getElementsByTagName('sub-element')->item(0)->nodeValue = "new val";
}
this kind of works but it removes the CDATA and just replaces it with new-val. I want to preserve the CDATA field so I tried the following:
$dom=new DOMDocument();
$dom->load("document.xml");
$ele=$root->getElementsByTagName('element');
foreach ($ele as $e) {
$sub=$e->getElementsByTagName('sub-element');
foreach($sub->childNodes as $child) {
if ($child->nodeType == XML_CDATA_SECTION_NODE) {
$child->nodeValue = 'new-val';
}
}
}
This seems like it should work but PHP returns the following Notice
Undefined property: DOMNodeList::$childNodes
Feel like I'm on the right path but I just can't figure out what I'm doing wrong here. Does anyone know how to fix?
My end goal output is:
<?xml version="1.0" encoding="utf-8"?>
<source>
<publisher>some-data</publisher>
<publisherurl>some-data</publisherurl>
<lastBuildDate>a-date</lastBuildDate>
<element>
<sub-element><![CDATA[new-val]]></sub-element>
</element>
</source>
You need to compare against firstChild
$xml = '<?xml version="1.0" encoding="utf-8"?>
<source>
<publisher>some-data</publisher>
<publisherurl>some-data</publisherurl>
<lastBuildDate>a-date</lastBuildDate>
<element>
<sub-element><![CDATA[some-data]]></sub-element>
</element>
<element>
<sub-element>some-other-data</sub-element>
</element>
</source>';
$dom = new DOMDocument();
$dom->loadXML($xml);
$ele=$dom->getElementsByTagName('element');
foreach ($ele as $e) {
$item = $e->getElementsByTagName('sub-element')->item(0);
if($item->firstChild->nodeType == XML_CDATA_SECTION_NODE) { //<------
//it's CDATA do whatever
$item->firstChild->nodeValue = "new val";
} else {
//it's not , do something else
$item->nodeValue = "new val";
}
}
echo "<pre>";
print_r(htmlentities($dom->saveXML()));
echo "</pre>";
Output:
<?xml version="1.0" encoding="utf-8"?>
<source>
<publisher>some-data</publisher>
<publisherurl>some-data</publisherurl>
<lastBuildDate>a-date</lastBuildDate>
<element>
<sub-element><![CDATA[new val]]></sub-element>
</element>
<element>
<sub-element>new val</sub-element>
</element>
</source>
PS: if you don't have to make a distinction between CDATA or not, just use firstChild
foreach ($ele as $e) {
$item = $e->getElementsByTagName('sub-element')->item(0);
$item->firstChild->nodeValue = "new val";
}

Convert XML File to Json fail

I don't understand what it's wrong on this code for read a XML File version 1.0 and convert to json
$xml = simplexml_load_file('/Volumes/ABKDatos/warehouse/tmp/1.xml');
libxml_use_internal_errors(true);
if ($xml === false)
{
echo "Error cargando XML".PHP_EOL;
foreach(libxml_get_errors() as $error) {
echo "\t", $error->message;
}
}
var_dump($xml->count());
$json = json_encode($xml);
$array = json_decode($json,TRUE);
var_dump($array)
show
int(0)
array(0) {
}
XML File
<?xml version="1.0" encoding="UTF-8"?><?xml-stylesheet type="text/xsl" href="/3.2/style/exchange.xsl"?>
<ops:world-patent-data xmlns="http://www.epo.org/exchange" xmlns:ops="http://ops.epo.org" xmlns:xlink="http://www.w3.org/1999/xlink">
<ops:biblio-search total-result-count="185">
<ops:query syntax="CQL">ti all "organic plastic" AND pd within "20070101,20170610"</ops:query>
<ops:range begin="1" end="100"/>
<ops:search-result>
<ops:publication-reference system="ops.epo.org" family-id="58738760">
<document-id document-id-type="docdb">
<country>US</country>
<doc-number>9665818</doc-number>
<kind>B1</kind>
</document-id>
</ops:publication-reference>
<ops:publication-reference system="ops.epo.org" family-id="53524784">
<document-id document-id-type="docdb">
<country>US</country>
<doc-number>2017121644</doc-number>
<kind>A1</kind>
</document-id>
</ops:publication-reference>
...
</ops:search-result>
</ops:biblio-search>
</ops:world-patent-data>

PHP - Parse, Read XML

Not too sure what I'm doing wrong with parsing/reading an xml document.
My guess is that it's not standardized, and I'm going to need a different process to read anything from the string.
If that's the case, then I'm rather excited to learn how someone would read the xml.
Here's what I've got, and what I'm doing.
example.xml
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="someurl.php"?>
<response>
<status>Error</status>
<error>The error message I need to extract, if the status says Error</error>
</response>
read_xml.php
<?php
$content = 'example.xml';
$string = file_get_contents($content);
$xml = simplexml_load_string($string);
print_r($xml);
?>
I'm getting no result back from the print_r.
I switched the xml to something more standard, like:
<?xml version="1.0" encoding="ISO-8859-1"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
...and it worked fine. So I'm sure it's due to a non-standard format, passed back from the source I'm getting it from.
How would I extract the <status> and <error> tags?
Tek has a good answer, but if you want to use SimpleXML, you can try something like this:
<?php
$xml = simplexml_load_file('example.xml');
echo $xml->asXML(); // this will print the whole string
echo $xml->status; // print status
echo $xml->error; // print error
?>
EDIT: If you have multiple <status> and <error> tags in your XML, have a look at this:
$xml = simplexml_load_file('example.xml');
foreach($xml->status as $status){
echo $status;
}
foreach($xml->error as $error){
echo $error;
}
I'm assuming <response> is your root. If it isn't, try $xml->response->status and $xml->response->error.
I prefer to use PHP's DOMDocument class better.
Try something like this:
<?php
$xml = '<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="someurl.php"?>
<response>
<status>Error</status>
<error>The error message I need to extract, if the status says Error</error>
</response>';
$dom = new DOMDocument();
$dom->loadXML($xml);
$statuses = $dom->getElementsByTagName('status');
foreach ($statuses as $status) {
echo "The status tag says: " . $status->nodeValue, PHP_EOL;
}
?>
Demo: http://codepad.viper-7.com/mID6Hp

PHP Flickr API - Retrieve Title from flickr.photosets.getInfo Response

I am getting the correct response from Flickr which is:
<?xml version="1.0" encoding="utf-8" ?>
<rsp stat="ok">
<photoset id="72157630469695108" owner="15823425#N00" primary="5110549866" secret="fd716fb5ee" server="1136" farm="2" photos="101" count_views="67" count_comments="0" count_photos="101" count_videos="0" can_comment="0" date_create="1341701808" date_update="1345054078">
<title>Montana</title>
<description />
</photoset>
</rsp>
For some reason I can't get the title, I've tried the following:
$album_info = simplexml_load_file($album_info_xml); // this is what the response is stored in
echo $album_info['photoset']['title'];
foreach($album_info->photoset as $ps) {
echo $ps['title'];
}
And a couple of other crazy things, I know it's something silly but don't know what it is I have missed.
Response can be seen here: http://www.flickr.com/services/api/explore/flickr.photosets.getInfo
Just use 72157630469695108 as the set id or alternatively use this url: http://api.flickr.com/services/rest/?method=flickr.photosets.getInfo&api_key=7ccedd2c89ca10303394b8085541d9de&photoset_id=72157630469695108
You should use SimpleXMLElement directly, then xpath to find your node.
$album_info = new SimpleXMLElement('<?xml version="1.0" encoding="utf-8" ?>
<rsp stat="ok">
<photoset id="72157630469695108" owner="15823425#N00" primary="5110549866" secret="fd716fb5ee" server="1136" farm="2" photos="101" count_views="67" count_comments="0" count_photos="101" count_videos="0" can_comment="1" date_create="1341701808" date_update="1345054078">
<title>Montana</title>
<description />
</photoset>
</rsp>'); // this is what the response is stored in
$result = $album_info->xpath('//title');
foreach ($result as $title)
{
echo $title . "\n";
}
Working example.
For anyone in the same position, this did the trick
$albumName = $album_info->photoset->title;

get Contents of the child tag using simeplxml_load_string in php

I have this XML
<parent>
<sms>
<response>
<message>message</message>
<reponse>text<response>
</response>
</sms>
<sms>
<response>
<message>message</message>
<reponse>text2<response>
</response>
</sms>
</parent>
I want to get the whole contents of response tag i.e <reponse1>text<response1> , <reponse2>text<response2> .which i will strore in an array. what i tried id
function xmlSplitUpResponseXML($xmlvalue)
{
$returnSplit = array();
$r = 0;
if(simplexml_load_string($xmlvalue))
{
$xml = simplexml_load_string($xmlvalue);
foreach($xml->children() as $child)
{
if(strtolower($child->getName())=='sms')
{
foreach ($child as $fields):
if(strtolower($fields->getName())=='response')
{
echo $fields;
}
}
} }
}
But the text is not echoed.
how can i do this.
Your XML isn't completly correct, but when fixed - try this:
echo $fields->message."<br>";
echo $fields->response."<hr>";
Works on your given example, with this fixed xml:
$string = "<parent><sms><response><message>message</message><response>text</response></response></sms><sms><response><message>message</message><response>text2</response></response></sms></parent>";
Hmm, seems like you need some XPath to the rescue...
Given the following fixed-up XML (note nested response nodes)
<parent>
<sms>
<response>
<message>message</message>
<response>text</response>
</response>
</sms>
<sms>
<response>
<message>message</message>
<response>text2</response>
</response>
</sms>
</parent>
The following PHP will do it for you.
<?php
$xml = simplexml_load_file( "sms.xml" );
// Find the sms response (note responses are nested in a parent response for some reason
$result = $xml->xpath('/parent/sms/response/response');
while(list( , $node) = each($result)) {
// to just output the value of the node
// echo $node;
// to wrap value in tags *bad idea*
echo $node->asXML();
}
?>
Not sure why you'd want to return an XML string, seems like a bad idea to me. What are you
doing with the output? Probably better to construct an XML document properly, just guessing...

Categories