Adding child node in xml file - php

I have an xml file
<?xml version="1.0" encoding="UTF-8"?>
<xml>
<settings>
<title>Calendar2</title>
<subTitle>Calendar2</subTitle>
</settings>
<events date="02-09-2010">
<event>
<title>HTML Tags</title>
<description>HTML Tags</description>
</event>
</events>
</xml>
How i can add another event inside events tag with respect to date
<?xml version="1.0" encoding="UTF-8"?>
<xml>
<settings>
<title>Calendar2</title>
<subTitle>Calendar2</subTitle>
</settings>
<events date="02-09-2010">
<event>
<title>HTML Tags</title>
<description>HTML Tags</description>
</event>
<event>
<title>Another Title</title>
<description>Another description</description>
</event>
</events>
</xml>
i used this code
$xml_str = file_get_contents($xmlfile);
$xml = new SimpleXMLElement($xml_str);
$event = $xml->events->addChild('event');
$event->addChild('title', 'More Parser Stories');
$event->addChild('description', 'This is all about the people who make it work.');
file_put_contents($xmlfile, $xml->asXML());
But it will add to the first node.How i can add to events tag with date 02-09-2010

You'll have to query for the wanted <events> tag instead of taking the first one (which what $xml->events would simply return), using xpath to query the xml document is helpful here:
PHP Script:
<?php
$xml_str = file_get_contents('xmlfile');
$xml = new SimpleXMLElement($xml_str);
$wantedEventsTag = $xml->xpath('/xml/events[#date="02-09-2010"]');
$wantedEventsTag = $wantedEventsTag [0];//since above fun will return an array
$wantedEventsTag['attrname']='attrval';//Here's how to add an attribute
$event = $wantedEventsTag->addChild('event');
$event->addChild('title', 'More Parser Stories');
$event->addChild('description', 'This is all about the people who make it work.');
file_put_contents('xmlfile.xml', $xml->asXML());
Sample XML File with multiple <events> tags:
<?xml version="1.0" encoding="UTF-8"?>
<xml>
<settings>
<title>Calendar2</title>
<subTitle>Calendar2</subTitle>
</settings>
<events date="01-01-1999">
</events>
<events>
</events>
<events date="02-09-2010">
<event>
<title>HTML Tags</title>
<description>HTML Tags</description>
</event>
<event>
<title>Another Title</title>
<description>Another description</description>
</event>
</events>
</xml>
the script xpath will match the required node, which we later use and add events subnodes to.

You'll need to use DOM instead, specifically DOMNode::insertBefore:
http://us.php.net/manual/en/domnode.insertbefore.php

Related

XML get nodes with sub nodes

I have the following XML structure:
As you can see, I have many nodes with the name "Activity"
Now I would like to know, how can I get all "Activity" nodes with their sub nodes?
I need a php solution and I tried something like that:
foreach($xml->Shipment->Package->children() as $activites) {
echo $activites->Status->StatusType->Description;
}
But this doesn't work.
Any ideas?
Thank you :)
Don't use children(), instead just iterate over the Activities.
For example:
<?php
$xml = '<?xml version="1.0" encoding="utf-8"?>
<TrackResponse>
<Shipment>
<Package>
<Activity>
<Status>
<StatusType>
<Description>Foo</Description>
</StatusType>
</Status>
</Activity>
<Activity>
<Status>
<StatusType>
<Description>Bar</Description>
</StatusType>
</Status>
</Activity>
<Activity>
<Status>
<StatusType>
<Description>Baz</Description>
</StatusType>
</Status>
</Activity>
</Package>
</Shipment>
</TrackResponse>';
$xml = simplexml_load_string($xml);
foreach ($xml->Shipment->Package->Activity as $activites) {
echo $activites->Status->StatusType->Description.PHP_EOL;
}
https://3v4l.org/BJDZC

Reading data from xml with php

please can anybody help me on how to retrieve data from the xml document below
<?xml version="1.0" encoding="utf-8"?>
<livescore-feed timestamp-created="1279745722">
<item id="afab6479053955afcd07dbe2eb972feb" status= "finished" timestamp-starts= "1278255600">
<teams>
<hosts id="zenspbfc_rus">
<name>Zenit</name>
<fullname>FC Zenit St. Petersburg</fullname>
</hosts>
<guests id="anzmfc_rus">
<name>Anzhi</name>
<fullname>FC Anzhi Makhachkala </fullname>
</guests>
</teams>
<events>
<event type="goal" team="hosts">
<player>Bystrov</player>
<minute>15</minute>
<score>1 - 0</score>
</event>
<event type="yellow_card" team="guests">
<player>Tsorayev</player>
<minute>40</minute>
</event>
</events>
</item>
</livescore-feed>
i have tried the following and i was able to some data, except from the events node, the events contains some nodes event. the problem i have is how to get the event from the events node
$xml = simplexml_load_string($data);
$match_id = $xml->{livescorefullname-feed}->matches->item[$i]['id'];
echo $match_id;
In SimpleXML, you don't specify the root node, because the SimpleXML object ($xml) is the root node.
This loops through each event and outputs the details.
foreach($xml->item->events->event as $event){
echo $event->score;
echo $event->player;
echo $event->attributes()->type;
echo $event->attributes()->team;
}

Xform xml parsing

In the xform xml i want to parse xml and access the id of node. It's the xform xml and i want to access the id of node test_geopoint (id=test_geopoint). But the node name will change for each xform xml.
<?php
$xmlstr = <<<XML <?xml version="1.0"?>
<h:html xmlns="http://www.w3.org/2002/xforms" xmlns:ev="http://www.w3.org/2001/xml-events" xmlns:h="http://www.w3.org/1999/xhtml" xmlns:jr="http://openrosa.org/javarosa" xmlns:orx="http://openrosa.org/xforms/" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<h:head>
<h:title>test_geopoint</h:title>
<model>
<instance>
<test_geopoint id="test_geopoint">
<name/>
<geopoint/>
<meta>
<instanceID/>
</meta>
</test_geopoint>
</instance>
</h:body>
</h:html> $XML;
i tried the code like this, but not access the id of node after the <instance>.
$movies = new SimpleXMLElement($xmlstr);
echo $movies->model->instance->children()[0]['id'];
and
echo $movies->head->title->model->instance->children()[0]['id'];
How can retrieve id of node next to <instance> in php ?
The below example is the same as you expecting, use it the same way I have accessed, the name in a array. You are suppose to mention as instanceId
$xmlstr = <<<XML
<?xml version='1.0' standalone='yes'?>
<movies>
<movie>
<title>PHP: Behind the Parser</title>
<characters>
<character>
<name>Ms. Coder</name>
<actor>Onlivia Actora</actor>
</character>
<character>
<name>Mr. Coder</name>
<actor>El ActÓr</actor>
</character>
</characters>
<plot>
So, this language. It's like, a programming language. Or is it a
scripting language? All is revealed in this thrilling horror spoof
of a documentary.
</plot>
<great-lines>
<line>PHP solves all my web problems</line>
</great-lines>
<rating type="thumbs">7</rating>
<rating type="stars">5</rating>
</movie>
</movies>
XML;
$movies = new SimpleXMLElement($xmlstr);
echo '<pre>';
foreach($movies as $moviesdata){
foreach($moviesdata as $moviesdatavalues){
foreach($moviesdatavalues as $mdvk=>$mdn){
foreach($mdn as $c=>$v){
if($c == 'name'){
echo $v."\n";
}
}
}
}
}
?>
The default namespace is http://www.w3.org/2002/xforms so every unprefixed element descendant of html is in that namespace; including your instance data.
Try adding an empty namespace (xmlns="") to your instance data...
<model>
<instance>
<test_geopoint xmlns="" id="test_geopoint">
<name/>
<geopoint/>
<meta>
<instanceID/>
</meta>
</test_geopoint>
</instance>
<bind nodeset="/test_geopoint/name" type="string"/>
<bind nodeset="/test_geopoint/geopoint" type="geopoint"/>
<bind calculate="concat('uuid:', uuid())" nodeset="/test_geopoint/meta/instanceID" readonly="true()" type="string"/>
</model>

cloneNode + appendChild + insertBefore dom xml php

I have an xml and I would be cloning father and leave under the cloned node.
More giving this error.
I wonder how
Fatal error: Call to a member function insertBefore() on a non-object in C:\xampp\htdocs\xml2\cloneNew.php on line 32
$xmla = <<<XML
<?xml version="1.0" ?>
<library>
<book isbn="1001" pubdate="1943-01-01">
<title><![CDATA[The Fountainhead]]></title>
<author>Ayn Rand</author>
<price>300</price>
</book>
<book isbn="1002" pubdate="1954-01-01">
<title><![CDATA[The Lord of the Rings]]></title>
<author>J.R.R.Tolkein</author>
<price>500</price>
</book>
<book isbn="1006" pubdate="1982-01-01">
<title><![CDATA[The Dark - Tower San]]></title>
<author>Stephen King</author>
<price>200</price>
</book>
</library>
XML;
$xmlb = <<<XML
<?xml version="1.0" ?>
<library>
<book isbn="1004" pubdate="1943-01-01">
<title><![CDATA[The Fountainhead]]></title>
<author>Ayn Rand</author>
<price>300</price>
</book>
</library>
XML;
$dom_01 = new DOMDocument();
$dom_01->loadXML($xmla);
$library_01 = $dom_01->documentElement;
$dom_02 = new DOMDocument();
$dom_02->loadXML($xmlb);
$library_02 = $dom_02->documentElement;
$xpath = new DOMXPath($dom_02);
$result = $xpath->query('/library/book[translate(#pubdate,"-","")>translate("1980-01-01","-","")]');
$library_02 = $library_02->cloneNode(true);
$newElement = $library_01->appendChild($result->item(0));
$library_01->parentNode->insertBefore($newElement, $result->item(0));
header("Content-type: text/xml");
echo $dom->saveXML();
Result:
$xmla = <<<XML
<?xml version="1.0" ?>
<library>
<book isbn="1001" pubdate="1943-01-01">
<title><![CDATA[The Fountainhead]]></title>
<author>Ayn Rand</author>
<price>300</price>
</book>
<book isbn="1002" pubdate="1954-01-01">
<title><![CDATA[The Lord of the Rings]]></title>
<author>J.R.R.Tolkein</author>
<price>500</price>
</book>
<book isbn="1004" pubdate="1943-01-01">
<title><![CDATA[The Fountainhead]]></title>
<author>Ayn Rand</author>
<price>300</price>
</book>
<book isbn="1006" pubdate="1982-01-01">
<title><![CDATA[The Dark - Tower San]]></title>
<author>Stephen King</author>
<price>200</price>
</book>
</library>
XML;
You are trying to get the parentNode of a documentElement no such node exists.
Also if you want to place a node from one document into another use DOMDocument.importNode instead of cloneNode.

Simple XML reading question (PHP)

I have the following XML file:
<?xml version="1.0" encoding="utf-8"?>
<SearchResults:searchresults xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.zillow.com/static/xsd/SearchResults.xsd /vstatic/279989c5e93d519f8d8f23d3f6cac661/static/xsd/SearchResults.xsd" xmlns:SearchResults="http://www.zillow.com/static/xsd/SearchResults.xsd">
<request>
<address>2114 Bigelow Ave</address>
<citystatezip>Seattle, WA</citystatezip>
</request>
<message>
<text>Request successfully processed</text>
<code>0</code>
</message>
<response>
<results>
<result>
<zpid>48749425</zpid>
<links>
<homedetails>http://www.zillow.com/homedetails/2114-Bigelow-Ave-N-Seattle-WA-98109/48749425_zpid/</homedetails>
<graphsanddata>http://www.zillow.com/homedetails/charts/48749425_zpid,1year_chartDuration/?cbt=3697699817560038867%7E3%7EQh4sEjEhBNEguUWA-0f22TvGUpBB7FpUkAZlBRy5_26R5PYjKDdVAA**</graphsanddata>
<mapthishome>http://www.zillow.com/homes/48749425_zpid/</mapthishome>
<myestimator>http://www.zillow.com/myestimator/Edit.htm?zprop=48749425</myestimator>
<myzestimator deprecated="true">http://www.zillow.com/myestimator/Edit.htm?zprop=48749425</myzestimator>
<comparables>http://www.zillow.com/homes/comps/48749425_zpid/</comparables>
</links>
<address>
<street>2114 Bigelow Ave N</street>
<zipcode>98109</zipcode>
<city>Seattle</city>
<state>WA</state>
<latitude>47.63793</latitude>
<longitude>-122.347936</longitude>
</address>
<zestimate>
<amount currency="USD">1112500</amount>
<last-updated>01/14/2010</last-updated>
<oneWeekChange deprecated="true"></oneWeekChange>
<valueChange duration="30" currency="USD">-77500</valueChange>
<valuationRange>
<low currency="USD">878875</low>
<high currency="USD">1145875</high>
</valuationRange>
<percentile>0</percentile>
</zestimate>
<localRealEstate>
<region id="271856" type="neighborhood" name="East Queen Anne">
<zindexValue>525,252</zindexValue>
<zindexOneYearChange>-0.104</zindexOneYearChange>
<links>
<overview>http://www.zillow.com/local-info/WA-Seattle/East-Queen-Anne/r_271856/</overview>
<forSaleByOwner>http://www.zillow.com/homes/fsbo/East-Queen-Anne-Seattle-WA/</forSaleByOwner>
<forSale>http://www.zillow.com/homes/for_sale/East-Queen-Anne-Seattle-WA/</forSale>
</links>
</region>
<region id="16037" type="city" name="Seattle">
<zindexValue>373,795</zindexValue>
<zindexOneYearChange>-0.064</zindexOneYearChange>
<links>
<overview>http://www.zillow.com/local-info/WA-Seattle/r_16037/</overview>
<forSaleByOwner>http://www.zillow.com/homes/fsbo/Seattle-WA/</forSaleByOwner>
<forSale>http://www.zillow.com/homes/for_sale/Seattle-WA/</forSale>
</links>
</region>
<region id="59" type="state" name="Washington">
<zindexValue>256,760</zindexValue>
<zindexOneYearChange>-0.074</zindexOneYearChange>
<links>
<overview>http://www.zillow.com/local-info/WA-home-value/r_59/</overview>
<forSaleByOwner>http://www.zillow.com/homes/fsbo/WA/</forSaleByOwner>
<forSale>http://www.zillow.com/homes/for_sale/WA/</forSale>
</links>
</region>
</localRealEstate>
</result>
</results>
</response>
</SearchResults:searchresults>
<!-- H:118 T:102ms S:1761 R:Fri Jan 15 10:52:49 PST 2010 B:3.0.79367-comp_rel_b -->
If you can't already tell, it's the standard output of the Zillow API. I want to store the data of information stored between certain tags, which I have learned is queried through the xpath.
For example, how would I query for the data in /SearchResults:searchresults/request/address? Doing something like this doesn't work when I echo/print the variable:
$xml = simplexml_load_file("-truncated XML URL-");
$result = $xml->xpath('/SearchResults:searchresults/request/address')
From what I understand, the $result variable should contain the value found nested in that %VALUE HERE%, correct? But it prints "Array", and when I print_r, it returns blank.
Here's a simple way to get that information:
<?php
$xml = simplexml_load_file("test.xml");
echo $xml->request->address;
?>
You need to use the full namespace not the short name.
Use http://simplepie.org
$xml = "yourxml code here";
$feed = new SimplePie();
$feed->set_raw_data($xml);
$feed->init();
$feed->handle_content_type();
echo $feed->get_adress();

Categories