I have made a search html page using IMDBAPI to create an xml file for that item I search. Then I have a php file that will parse through that file and only pull the data I want from the xml file to display. Everything seems to be working as I am getting a blank white page. The issue is that nothing is displaying.
Part of the XML
<IMDBDocumentList>
<item>
<rating>8.7</rating>
<rating_count>10301</rating_count>
<year>1999</year>
<genres>
<item>Animation</item>
<item>Action</item>
<item>Adventure</item>
<item>Comedy</item>
<item>Drama</item>
<item>Fantasy</item>
<item>Romance</item>
</genres>
<rated>PG</rated>
<title>Wan pîsu: One Piece</title>
<imdb_url>http://www.imdb.com/title/tt0388629/</imdb_url>
<directors>
<item>Kônosuke Uda</item>
</directors>
<actors>
<item>Mayumi Tanaka</item>
<item>Kazuya Nakai</item>
<item>Akemi Okamura</item>
<item>Kappei Yamaguchi</item>
<item>Mahito Ôba</item>
<item>Hiroaki Hirata</item>
<item>Colleen Clinkenbeard</item>
<item>Ikue Ôtani</item>
<item>Chikao Ôtsuka</item>
<item>Yuriko Yamaguchi</item>
<item>Luci Christian</item>
<item>Christopher Sabat</item>
<item>Sonny Strait</item>
<item>Kazuki Yao</item>
</actors>
PHP Parse
$lib = simplexml_load_file("test.xml");
$xml = $lib->IMDBDocumentList->item;
$rating = $xml->rating;
$year = $xml->year;
print $rating;
print $year;
IMDBDocumentList is your root node, so you don't need to address it:
$xml = $lib->item;
Related
I just wanted to ask how I can insert a new node in an XML using PHP. my XML file (questions.xml) is given below
<?xml version="1.0" encoding="UTF-8"?>
<Quiz>
<topic text="Preparation for Exam">
<subtopic text="Science" />
<subtopic text="Maths" />
<subtopic text="english" />
</topic>
</Quiz>
I want to add a new "subtopic" with the "text" attribute, that is "geography". How can I do this using PHP? Thanks in advance though.
well my code is
<?php
$xmldoc = new DOMDocument();
$xmldoc->load('questions.xml');
$root = $xmldoc->firstChild;
$newElement = $xmldoc->createElement('subtopic');
$root->appendChild($newElement);
// $newText = $xmldoc->createTextNode('geology');
// $newElement->appendChild($newText);
$xmldoc->save('questions.xml');
?>
I'd use SimpleXML for this. It would look somehow like this:
// Open and parse the XML file
$xml = simplexml_load_file("questions.xml");
// Create a child in the first topic node
$child = $xml->topic[0]->addChild("subtopic");
// Add the text attribute
$child->addAttribute("text", "geography");
You can either display the new XML code with echo or store it in a file.
// Display the new XML code
echo $xml->asXML();
// Store new XML code in questions.xml
$xml->asXML("questions.xml");
The best and safe way is to load your XML document into a PHP DOMDocument object, and then go to your desired node, add a child, and finally save the new version of the XML into a file.
Take a look at the documentation : DOMDocument
Example of code:
// open and load a XML file
$dom = new DomDocument();
$dom->load('your_file.xml');
// Apply some modification
$specificNode = $dom->getElementsByTagName('node_to_catch');
$newSubTopic = $xmldoc->createElement('subtopic');
$newSubTopicText = $xmldoc->createTextNode('geography');
$newSubTopic->appendChild($newSubTopicText);
$specificNode->appendChild($newSubTopic);
// Save the new version of the file
$dom->save('your_file_v2.xml');
You can use PHP's Simple XML. You have to read the file content, add the node with Simple XML and write the content back.
I have I'm trying to get the "extract" node value from an xml file/url. Below is my code, but I'm not getting any output.
<?php
$url = "https://en.wikipedia.org/w/api.php?format=xml&action=query&prop=extracts&exintro=&explaintext=&titles=unix";
$xml = simplexml_load_file($url);
echo $xml->extract ;
?>
Any help would be greatly appreciated.
$xml->extract would work if the node was a direct child of the xml file.
After looking at the api response, I am able to get and display the extract node using the full path:
$url = "https://en.wikipedia.org/w/api.php?format=xml&action=query&prop=extracts&exintro=&explaintext=&titles=unix";
$xml = simplexml_load_file($url);
echo $xml->query->pages->page->extract ;
Ok, please bear with me as I explain this app. The first view shows a tableview, where each row is a 'request' that someone has made, also using the app. The requests are actually a parsed xml file that looks something like this:
<item>
<title>Request</title>
<name>Name</name>
<Responses>0</Responses>
</item>
Using the script listed underneath this paragraph, I am able to run some code in iOS that will take text from text-boxes in the app, and append the XML with a new item set.
<?php
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$request = $_POST['request'];
$anon = $_POST['anon'];
$pubDate = $_POST['pubDate'];
$loc = $_POST['loc'];
//This line will load the XML file
$xml = simplexml_load_file("URL.xml") or die("Not loaded!\n");
//print_r($xml);
//This line gets the channel element (from an array returned by the xpath method)
$channel = $xml->xpath('//channel');
$channel = $channel[0];
//print_r($channel);
$person = $channel->addChild("item");
$person->addChild("first_name", $firstName);
$person->addChild("last_name", $lastName);
$person->addChild("title", $request);
$person->addChild("date", $pubDate);
$person->addChild("anonymous", $anon);
$person->addChild("responses", "0");
$person->addChild("location", $loc);
//This next line will overwrite the original XML file with new data added
$xml->asXML("Test.xml");
?>
The actual XML has much more listed than what I put at the beginning, I just edited it down to save space, so that's why it and the PHP don't quite match up.
All of this works great, the app parses the XML to show what has been requested, and a user can make a new request that will then show in the app.
My problem is that when someone responds to an existing request, I would like the <Responses> to increase by 1. Is there something I can do with a different script that would find that entry, and +1 to whatever number currently exists in that item's Response tag?
I have seen this script, but it appears to go through and search for all of a certain tag, and change all tags of that name in the XML. I am looking to just find one specific one and change it. Suggestions?
$str = <<<XML
<ScrapBook>
<Event>
<Name> Name of Event </Name>
<Blah>glop glop</Blah>
</Event>
</ScrapBook>
XML;
$xmlDoc = new DOMDocument();
$xmlDoc->loadXml($str);
$events = $xmlDoc->getElementsByTagName("Event");
foreach($events as $event){
$eventNames = $event->getElementsByTagName("Name");
$eventN = $eventNames->item(0)->nodeValue;
if(' Name of Event ' == $eventN){
$eventNames->item(0)->nodeValue = 'New name';
}
}
var_dump($xmlDoc->saveXML());
You can go with simplexml to do that; first, select the <item> to be changed, then store the new <Responses>:
$xml = simplexml_load_string($x); // assume XML in $x
// select <Responses> with xpath by title and name
$responses = $xml->xpath("/items/item[title = 'Foo' and name = 'Bar']/Responses");
// store number + 1
$responses[0][0] = $responses[0] + 1;
see it working: https://eval.in/127882
I am trying to write a code where it will find a specific element in my XML file and then change the value of the text node. The XML file has different namespaces. Till now, I have managed to register the namespaces and also echo the text node of the element, which I want to change.
<?php
$xml = simplexml_load_file('getobs.xml');
$xml->registerXPathNamespace('g','http://www.opengis.net/gml');
$result = $xml->xpath('//g:beginPosition');
foreach ($result as $title) {
echo $title . "\n";
}
?>
My question is: How can I change the value of this element using SimpleXML? I tried to use the nodeValue command but I am not able to make it work.
This is a part of the XML:
<sos:GetObservation xmlns:sos="http://www.opengis.net/sos/1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" service="SOS" version="1.0.0" srsName="urn:ogc:def:crs:EPSG:4326">
<sos:offering>urn:gfz:cawa:def:offering:meteorology</sos:offering>
<sos:eventTime>
<ogc:TM_During xmlns:ogc="http://www.opengis.net/ogc" xsi:type="ogc:BinaryTemporalOpType">
<ogc:PropertyName>urn:ogc:data:time:iso8601</ogc:PropertyName>
<gml:TimePeriod xmlns:gml="http://www.opengis.net/gml">
<gml:beginPosition>2011-02-10T01:10:00.000</gml:beginPosition>
Thanks
Dimitris
In the end I managed to do it by using the PHP XML DOM.
Here is the code that I used in order to change the text node of a specific element:
<?php
// create new DOM document and load the data
$dom = new DOMDocument;
$dom->load('getobs.xml');
//var_dump($dom);
// Create new xpath and register the namespace
$xpath = new DOMXPath($dom);
$xpath->registerNamespace('g','http://www.opengis.net/gml');
// query the result amd change the value to the new date
$result = $xpath->query("//g:beginPosition");
$result->item(0)->nodeValue = 'sds';
// save the values in a new xml
file_put_contents('test.xml',$dom->saveXML());
?>
Not wanting to switch from the code I've already made for SimpleXML, I found this solution:
http://www.dotdragnet.com/forum/index.php?topic=3979.0
Specificially:
$numvotes = $xml->xpath('/gallery/image[path="'.$_GET["image"].'"]/numvotes');
...
$numvotes[0][0] = $votes;
Hope this helps!
I have source XML here: http://www.grilykrby.cz/rss/pf-heureka.xml. I want to use this xml feed and create another modified on my own server. I would like to change every node CATEGORYTEXT which contains word Prislusenstvi. I just tried something but I got only the listing of all categories without changing XML :-(
Here is the example of my code. The row $kategorie="nejaka kategorie"; doesn't work.
<?php
$file = "http://www.grilykrby.cz/rss/pf-heureka.xml";
$xml=simplexml_load_file($file);
foreach ($xml->xpath('//SHOPITEM/CATEGORYTEXT') as $kategorie) {
echo $kategorie."<br />";
$kategorie="nejaka kategorie";
}
file_put_contents('test.xml', $xml->asXML());
?>
$kategorie is just a temp variable used in the loop which contains a copy of the data returned by xpath query. You would need to actually set the value directly in the $xml object.
I would personally also consider doing a str_replace or preg_replace within the XML content itself before parsing it into a simpleXML object.
Final Accepted Answer
<?php
$xml = simplexml_load_file('http://www.grilykrby.cz/rss/pf-heureka.xml');
$i=0;
foreach($xml -> SHOPITEM as $polozka) {
if ($polozka -> CATEGORYTEXT == "Příslušenství") $xml -> SHOPITEM[$i] -> CATEGORYTEXT = "Some other text";
$i++;
}
?>