Convert XML formatted list into PHP - php

I have a URL that returns an XML formatted list
i have put this URL in a variable:
$url = 'urlHere.xml';
i need to be able to return the results and list them in PHP (for example in a select element)
i have tried using the following:
$xml = simplexml_load_file($url);
but im not too sure what would be next
the start of the XML file looks like:
<interface-response>
<tldlist>
<tld>
<tld>com</tld>
</tld>
<tld>
<tld>net</tld>
</tld>

Assume this is our xml file stored in the same dir
sms.xml
<?xml ?>
<sms>
<body>
Hi Doe! whats going on?
</body>
</sms>
Now lets get the contant of sms.xml in php
<?php
$xml = simplexml_load_file("sms.xml");
echo $xml->body;
?>
Output :
Hi Doe! whats going on?

Related

Getting content out of a json object

I use XML feeds in my website, which I convert to json before adding them to my database. Until now my code has pretty much done it's job. But now I have got the following problem:
Usually the structure looks like this:
<surface_area>
<built>330</built>
<plot>2980</plot>
</surface_area>
<location>
<latitude>0</latitude>
<longitude>0</longitude>
</location>
And by using the following code I can get the information from the object I need:
$lat = $opened_json_file->location->latitude;
However, the structure of one of the feeds looks like this:
<desc>
<en>
<![CDATA[
This is an example.
]]>
</en>
</desc>
The description itself is another object which contains the data. My question: How do I call upon this data and save it in a variable to insert into the database?
Wanted outcome:
$desc = $opened_json_file->desc->en->??;
echo $desc;
This is an example.

PHP XML string parsing returns "Trying to get property of non-object"

Im trying to export some data from here (XML)
e.g and
For example i'm trying to get the by using this code:
$xml = simplexml_load_string($response);
$results = $xml->Iteration[0]->{'Iteration_query-def'};
The thing is that returns the Notice written in post's title.
Am i loosing something in the path of XML file ?
Thank you.
try simplexml_load_file() to fetch data from url
$xml = simplexml_load_file('http://blast.ncbi.nlm.nih.gov/Blast.cgi?CMD=Get&RID=VY1DT6CN014&FORMAT_TYPE=XML');
echo $results = (string)$xml->BlastOutput_iterations->Iteration[0]->{'Iteration_query-def'};
Please notice structure of XML document. There is a parent for Iteration called 'BlastOutput_iterations'. Please try below script.
$results = $xml->BlastOutput_iterations->Iteration[0]->{'Iteration_query-def'};

XML file content not updating using PHP

Each time I run the code, file updates and I can see the file last edited date and time are updated but the content in the XML file is not updated.
I just tried to update the following XML Code
<?xml version="1.0" encoding="utf-8"?>
<topcont>
<sitenondualtraining>
<title>The Heart of Awakening</title>
<descripition>nondual</descripition>
<link>www.test.com/post/latestpost</link>
</sitenondualtraining>
</topcont>
using PHP code
$topcont = new DOMDocument();
$topcont->load("http://fenner.tk/topcont.xml");
$topcont->topcont->sitenondualtraining->title = 'test';
$topcont->sitenondualtraining->descripition = $_POST['nd2'];
$topcont->sitenondualtraining->link = $_POST['nd3'];
$topcont->Save("topcont.xml");
I also tried
$topcont = new SimpleXmlElement('http://fenner.tk/topcont.xml',null, true);
$topcont->sitenondualtraining->title = $_POST['nd1'];
$topcont->sitenondualtraining->descripition = $_POST['nd2'];
$topcont->sitenondualtraining->link = $_POST['nd3'];
$topcont->asXml('topcont.xml');
But none of these are working. Can anyone point where the issue is? Thanks.
File permission are set to 777 but still not working
NO ERRORS BUT WARNINGS ARE
Warning: Creating default object from empty value in /home/fenner/public_html/topads.php on line 20
Warning: Creating default object from empty value in /home/fenner/public_html/topads.php on line 21 /home/fenner/public_html/
Using DomDocument, you were almost there. You can do it like this:
$topcont = new DOMDocument();
$topcont->load("topcont.xml");
$topcont->getElementsByTagName("title")->item(0)->nodeValue = $_POST['nd2'];
$topcont->getElementsByTagName("description")->item(0)->nodeValue = $_POST['nd2'];
$topcont->getElementsByTagName("link")->item(0)->nodeValue = $_POST['nd3'];
$topcont->save("topcont.xml");
Just remember to sanitize your inputs before storing your data ;)
Also worth looking into is creating cdata sections and using replaceData, depending on what you intend to store in each node.
EDIT
In response to your comment below, you might want to change your xml structure a little if you are going to be handling multiple child nodes. This way it is easier to loop through and update the node you are interested in. You will see below that I moved 'sitenondualtraining' and 'siteradiantmind' to be id's of an 'item" node, though you could easily change this to something like <site id="nodualtraining> if that's more like what you were looking for.
<?xml version="1.0" encoding="utf-8"?>
<topcont>
<item id="sitenondualtraining">
<title>test</title>
<description>hello test</description>
<link>hello</link>
</item>
<item id="siteradiantmind">
<title>The Heart of Awakening</title>
<description>radiantmind</description>
<link>www.radiantmind.com/post/latestpost</link>
</item>
</topcont>
Your PHP code would then be something like this, again this is quite basic and could be tidied up, but is a good start:
$items = $topcont->getElementsByTagName("item");
// loop through each item
foreach ($items as $item) {
$id = $item->getAttribute('id');
// check the item id to make sure we edit the correct one
if ($id == "sitenondualtraining") {
$item->getElementsByTagName("title")->item(0)->nodeValue = $_POST['nd1'];
$item->getElementsByTagName("link")->item(0)->nodeValue = $_POST['nd2'];
$item->getElementsByTagName("description")->item(0)->nodeValue = $_POST['nd3];
}
}
If you were feeling a little adventurous, you could have a look at xpath and xpath query, you can find some sample code in most php docs to get you started and the comments from other users can be helpful as well.
For reference: getAttribute, getElementsByTagName.

Parsing the Google Reader export

I am attempting to use SimpleXML to parse the xml file that is produced from the Google Reader export.
File example:
<?xml version="1.0" encoding="UTF-8"?>
<opml version="1.0">
<head>
<title>TheTechBox subscriptions in Google Reader</title>
</head>
<body>
<outline text="Engadget RSS Feed" title="Engadget RSS Feed"
type="rss" xmlUrl="http://www.engadget.com/rss.xml" htmlUrl="http://www.engadget.com"/>
<outline text="xkcd.com" title="xkcd.com" type="rss"
xmlUrl="http://xkcd.com/rss.xml" htmlUrl="http://xkcd.com/"/>
</body>
</opml>
This is what I have tried so far, the user uploads the file to this form and the form needs to loop through and extract the data.
<?php
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br>";
}
else
{
$import = new SimpleXMLElement($_FILES["file"]["name"]);
foreach($import->opml->body->outline[0] as $feed){
echo $feed["title"];
}
}
?>
Right now chrome produces a server error which indicates something is very wrong on the page, the file uploads OK so it appears to be the simpleXML part.
I am planning to do something more complex with the data later, I am currently trying to get it just to echo the data on the page (for demo purposes).
Any feedback would be greatly appreciated.
Here is the working code in the end
$import = simplexml_load_file($_FILES["file"]["tmp_name"]);
foreach($import->body->outline as $feed){
echo $feed["title"];
}
This will need adding to to parse all of the data but this works.
You've fallen into a classic trap when using SimpleXML: the first object you get when parsing a file or string is not an abstract "document" object, but the parent node. In this case, the parent node is <opml> ... </opml>, so $import in your sample code is that <opml> node. In other words, rather than $import->opml->body you just need to say $import->body.
There's another bug in your loop as well, which is that you are asking for the first <outline> element (->outline[0]) when what you want is to be looping over all of the elements (foreach( $whatever->outline as $feed )).

Using SimpleXML to get twitter avatar url (weird)

Im using simplexml to get the twitter profile avatar url from the xml status page.
this is the code im using
<?
$username = twitter;
$xml = simplexml_load_file("http://twitter.com/users/".$username.".xml");
echo $xml->user->profile_image_url;
?>
The xml page loads when i visit it, but for some reason nothing is being echoed. No errors. Nothing.
When i visit it in a browser, i get this:
<?xml version="1.0" encoding="UTF-8"?>
<user>
<id>783214</id>
<name>Twitter</name>
<screen_name>twitter</screen_name>
<location>San Francisco, CA</location>
<description>Always wondering what everyone's doing.</description>
<profile_image_url>http://a1.twimg.com/profile_images/75075164/twitter_bird_profile_normal.png</profile_image_url>
<url>http://twitter.com</url>.....
(the rest is long and irrelevant to the question)
The data is there, why wont it echo?
After loading the XML document, the root element user is represented by the SimpleXMLElement object saved in $xml. Therefore $xml->user does not exist.
This one should work:
<?
$username = "twitter"; // <-- You did not use quotes here?! Typo?
$xml = simplexml_load_file("http://twitter.com/users/".$username.".xml");
echo $xml->profile_image_url; // <-- No $xml->user here!
?>
It is because the root element (in this case, <user>) is implied - you do not have to specify it.
Try this:
echo $xml->profile_image_url;
hey guys - tried out twivatar but I was getting an error 500 error????
anyway here is the code I ended up using - how it is helpful
<?php
if (isset($_REQUEST['user']))
//if "user" is filled out, get the user's twitter picture
{
$username = $_REQUEST['user'];
}else{
$username = 'aplusk';
//else lets use ashton kutcher's picture just for the F of it
} // <-- You did not use quotes here?! Typo?
$xml = simplexml_load_file("http://twitter.com/users/".$username.".xml");
$timage = $xml->profile_image_url; // <-- No $xml->user here!
header('location: ' . $timage);
?>
Now it is extremely easy to call this script from anywhere in your application simply print ...
<img src="http://mywebapp.org/timage.php?user=<php echo $data['twitter_screen_name'];?>" />
Twivatar
Previously, the easiest way to get the twitter avatar was to use Twivatar, which was built by Remy Sharp. However the service has since been shut down.
Using a third party for this is unnecessary.

Categories