want to make loop and Parsing XML CDATA
my XML
<?xml version="1.0"?>
<photos>
<photo image="images/1.jpg" url="http://LINKHERE" target="_blank" id="1">
</photo>
<photo image="images/1.jpg" url="http://LINKHERE" target="_blank" id="2">
</photo>
</photos>
my code
for ($x = 1; $x <= 10; $x++) {
$dom=new DOMDocument();
$xml='images.xml';
$dom->load($xml);
$xp = new DomXPath($dom);
//$item_content = $xp->query("//*[#id = $x]");
foreach ($dom->getElementsByTagName('photos') as $item) {
$cdata=$dom->createCDATASection('<head>test'.$x.'</head><body></body>');
$item->getElementsByTagName('photo')->item(0)->appendChild($cdata);
}
$dom->save($xml);
}
but the result
<photo image="images/1.jpg" url="http://LINKHERE" target="_blank" id="1">
<![CDATA[<head>test1</head><body></body><head>test2</head><body></body><head>test3</head><body></body>
<head>test4</head><body></body><head>test5</head><body></body>
<head>test6</head><body></body><head>test7</head>
<body></body><head>test8</head><body></body><head>test9</head><body></body>]]><![CDATA[<head>test10</head><body>
</body>]]></photo>
<photo image="images/2.jpg" url="http://http://LINKHERE" target="_blank" id="2">
</photo>
i want it be this
<photo image="images/1.jpg" url="http://LINKHERE" target="_blank" id="1">
<![CDATA[<head>test1</head><body></body>]]></photo>
<photo image="images/2.jpg" url="http://http://LINKHERE" target="_blank" id="2">
<![CDATA[<head>test2</head><body></body>]]></photo>
i want move on loop by id
i try many times but no way , i think i have a problem on my loop
need some help here
You want to append CData on each photo element, so you should loop through photo instead of photos, for example :
$raw = <<<XML
<photos>
<photo image="images/1.jpg" url="http://LINKHERE" target="_blank" id="1">
</photo>
<photo image="images/1.jpg" url="http://LINKHERE" target="_blank" id="2">
</photo>
</photos>
XML;
$dom = new DOMDocument();
$dom->loadXML($raw);
$x = 1;
foreach ($dom->getElementsByTagName('photo') as $item) {
$cdata=$dom->createCDATASection('<head>test'.$x.'</head><body></body>');
$item->appendChild($cdata);
$x++;
}
echo $dom->saveXML($xml);
eval.in demo
output :
<?xml version="1.0"?>
<photos>
<photo image="images/1.jpg" url="http://LINKHERE" target="_blank" id="1">
<![CDATA[<head>test1</head><body></body>]]></photo>
<photo image="images/1.jpg" url="http://LINKHERE" target="_blank" id="2">
<![CDATA[<head>test2</head><body></body>]]></photo>
</photos>
Try this code
<?php
$dom=new DOMDocument();
$xml='images.xml';
$dom->load($xml);
$xp = new DomXPath($dom);
$i = 0;
foreach ($dom->getElementsByTagName('photo') as $item) {
$cdata=$dom->createCDATASection('<head>test'.($i+1).'</head><body></body>');
$item->appendChild($cdata);
$i ++;
}
$dom->save($xml);
Related
I want to delete a node by id in XML my code is this:
$id=$_GET["id"];
$usuarios= simplexml_load_file('cart.xml');
if($_GET["action"] == "delete"){
foreach($usuarios->carro as $elemento){
if($elemento['id'] == $id) {
echo '<script>alert("delete")</script>';
unset($elemento['id']);
}
}
}
but doesn't work.
My XML cart.xml:
<?xml version="1.0"?>
<info>
<carro id="0">
<usuario>alex</usuario>
<producto>instict</producto>
<Size>CH</Size>
<cantidad>1</cantidad>
<precio>100</precio>
</carro>
<carro id="1">
<usuario>alex</usuario>
<producto>instict</producto>
<Size>G</Size>
<cantidad>1</cantidad>
<precio>100</precio>
</carro>
<carro id="2">
<usuario>alex</usuario>
<producto>instict</producto>
<Size>G</Size>
<cantidad>1</cantidad>
<precio>100</precio>
</carro>
<carro id="3">
<usuario>Gera</usuario>
<producto>instict</producto>
<Size>M</Size>
<cantidad>1</cantidad>
<precio>100</precio>
</carro>
</info>
I want to delete for example id="2" so the output would be:
<?xml version="1.0"?>
<info>
<carro id="0">
<usuario>alex</usuario>
<producto>instict</producto>
<Size>CH</Size>
<cantidad>1</cantidad>
<precio>100</precio>
</carro>
<carro id="1">
<usuario>alex</usuario>
<producto>instict</producto>
<Size>G</Size>
<cantidad>1</cantidad>
<precio>100</precio>
</carro>
<carro id="3">
<usuario>Gera</usuario>
<producto>instict</producto>
<Size>M</Size>
<cantidad>1</cantidad>
<precio>100</precio>
</carro>
</info>
Change
$usuarios->carro as $key => $elemento
and then
unset($usuarios->carro[$key]);
and then write result in new file as string
file_put_contents('newfile.xml', $usuarios->asXML());
XML:
<Result xmlns="" xmlns:xsi="" totalResultsAvailable="0" totalResultsReturned="0" schk="true" totalLooseOffers="0" xsi:schemaLocation="">
<details>
<ID></ID>
<applicationVersion>1.0</applicationVersion>
<applicationPath/>
<date>2016-05-23T12:17:16.369-03:00</date>
<elapsedTime>17</elapsedTime>
<status>success</status>
<message>success</message>
</details>
<category id="1">
<thumbnail url="http://image.google.com/test.jpg"/>
<links>
<link url="www.google.com" type="category"/>
<link url="www.google2.com" type="xml"/>
</links>
<name>Category</name>
<filters>
<filter id="1" name="Filter1">
<value id="1" value="Test1"/>
<value id="2" value="Test2"/>
<value id="3" value="Test3"/>
</filter>
<filter id="2" name="Filter2">
<value id="1" value="Test4"/>
<value id="2" value="Test5"/>
<value id="3" value="Test6"/>
</filter>
</filters>
</category>
</Result>
PHP:
$xml = simplexml_load_file("http://xml.com");
foreach($xml->category->filters as $filters){
foreach($filters->children() as $child){
echo $child['value'];
}
}
I'm trying to get the filters value, but nothing shows with the code i have. I saw something about xpath but don't know if it's applicable in this situation. Do you have any clue?
--
When the XML looks like this:
<Result xmlns="" xmlns:xsi="" totalResultsAvailable="0" totalResultsReturned="0" schk="true" totalLooseOffers="0" xsi:schemaLocation="">
<details>
<ID></ID>
<applicationVersion>1.0</applicationVersion>
<applicationPath/>
<date>2016-05-23T12:17:16.369-03:00</date>
<elapsedTime>17</elapsedTime>
<status>success</status>
<message>success</message>
</details>
<subCategory id="1">
<thumbnail url="http://image.google.com/test.jpg"/>
<name>Subcategory</name>
</subCategory>
<subCategory id="2">
<thumbnail url="http://image.google.com/test2.jpg"/>
<name>Subcategory2</name>
</subCategory>
</Result>
Then am able to do this:
foreach($xml->subCategory as $subCategory){
$categoryId = $subCategory['id'];
$categoryName = $subCategory->name;
}
The elements you reference as $child in the inner loop actually point to the <filter> nodes, not the children <value> nodes you are attempting to target attributes for. So this really is just a matter of extending the outer foreach loop to iterate over $xml->category->filters->filter rather than its parent $xml->category->filters.
// Iterate the correct <filter> node, not its parent <filters>
foreach ($xml->category->filters->filter as $filter) {
foreach($filter->children() as $child){
echo $child['value'] . "\n";
}
}
Here it is in demonstration: https://3v4l.org/Rqc4Y
Using xpath, you can target the inner nodes directly.
$values = $xml->xpath('//category/filters/filter/value');
foreach ($values as $value) {
echo $value['value'];
}
https://3v4l.org/vPhKE
Both of these examples output
Test1
Test2
Test3
Test4
Test5
Test6
I'm looking to parse out only the content of the element below into its own XML document, but am unsure of the proper PHP method to use. XML data in boxb.php is unable to be modified.
EX:
Parsing code:
<?php
include 'boxb.php';
$boxb = new SimpleXMLElement($xmlstr);
$boxb->ad[0]->content;
echo $boxb->ad[0]->content;
?>
boxb.php contains the following:
<?php
$xmlstr = <<<XML
<boxb>
<ad type="agnostic_template">
<url><![CDATA[http://ads.cookie.com/8/redir/1db04901-225e-11e4-86f3-bc305bf4914b/0/632361]]></url>
<track />
<content>
<VAST version="2.0">
<Ad id="228">
<InLine>
<AdSystem version="4.11.0-10">LiveRail</AdSystem>
<AdTitle><![CDATA[TV Overlay PNG]]></AdTitle>
<Description />
<Error><![CDATA[http://t4.liverail.com/?metric=error&erc=[ERRORCODE]&pos=1&coid=135&pid=1331&nid=1331&oid=228&olid=2281331&cid=8455&tpcid=&vid=&amid=&cc=default&pp=&vi=0&vv=&sg=&tsg=&pmu=0&pau=0&psz=0&ctx=&tctx=&coty=7&adt=0&did=&buid=&scen=&mca=&mma=&mct=0&url=http%3A%2F%2Fwww.iab.net%2Fguidelines%2F508676%2Fdigitalvideo%2Fvast%2Fvast_xml_samples&trid=53ea9957dc20a5.06241648&bidf=0.00000&bids=0.00000&bidt=1&bidh=0&bidlaf=0&cb=6662.66.104.228.162.0&ver=1&w=&wy=&x=&y=&xy=&redirect=]]></Error>
<Impression id="LR"><![CDATA[http://t4.liverail.com/?metric=impression&cofl=0&flid=0&pos=1&coid=135&pid=1331&nid=1331&oid=228&olid=2281331&cid=8455&tpcid=&vid=&amid=&cc=default&pp=&vi=0&vv=&sg=&tsg=&pmu=0&pau=0&psz=0&ctx=&tctx=&coty=7&adt=0&did=&buid=&scen=&mca=&mma=&mct=0&url=http%3A%2F%2Fwww.iab.net%2Fguidelines%2F508676%2Fdigitalvideo%2Fvast%2Fvast_xml_samples&trid=53ea9957dc20a5.06241648&bidf=0.00000&bids=0.00000&bidt=1&bidh=0&bidlaf=0&cb=6662.66.104.228.162.0&ver=1&w=&wy=&x=29&y=29&xy=9dae&z2=0.00000]]></Impression>
<Impression id="QC"><![CDATA[http://pixel.quantserve.com/pixel/p-d05JkuPGiy-jY.gif?r=6662]]></Impression>
<Impression id="CS"><![CDATA[http://b.scorecardresearch.com/p?c1=1&c2=9864668&c3=1331&c4=&c5=09]]></Impression>
<Impression><![CDATA[http://load.exelator.com/load/?p=104&g=440&j=0]]></Impression>
<Impression><![CDATA[http://navdmp.com/usr?vast=http%3A%2F%2Ft4.liverail.com%2F%3Fmetric%3Dmsync%26p%3D78]]></Impression>
<Impression><![CDATA[http://pixel.tapad.com/idsync/ex/receive?partner_id=LIVERAIL&partner_device_id=97838239447]]></Impression>
<Impression><![CDATA[http://t4.liverail.com/?metric=rsync&p=3016&redirect=http%3A%2F%2Fliverail2waycm-atl.netmng.com%2Fcm%2F%3Fredirect%3Dhttp%253A%252F%252Ft4.liverail.com%252F%253Fmetric%253Dcsync%2526p%253D3016%2526s%253D(NM-UserID)]]></Impression>
<Impression><![CDATA[http://t4.liverail.com/?metric=rsync&p=3017&redirect=http%3A%2F%2Fm.xp1.ru4.com%2Factivity%3F_o%3D62795%26_t%3Dcm_rail]]></Impression>
<Impression><![CDATA[http://n.us1.dyntrk.com/adx/lr/sync_lr.php?lrid=97838239447]]></Impression>
<Creatives>
<Creative sequence="1" id="8455">
<NonLinearAds>
<NonLinear width="300" height="60">
<StaticResource creativeType="image/png"><![CDATA[http://cdn.liverail.com/adasset/228/8455/overlay.png]]></StaticResource>
<NonLinearClickThrough><![CDATA[http://t4.liverail.com/?metric=clickthru&pos=1&coid=135&pid=1331&nid=1331&oid=228&olid=2281331&cid=8455&tpcid=&vid=&amid=&cc=default&pp=&vi=0&vv=&sg=&tsg=&pmu=0&pau=0&psz=0&ctx=&tctx=&coty=7&adt=0&did=&buid=&scen=&mca=&mma=&mct=0&url=http%3A%2F%2Fwww.iab.net%2Fguidelines%2F508676%2Fdigitalvideo%2Fvast%2Fvast_xml_samples&trid=53ea9957dc20a5.06241648&bidf=0.00000&bids=0.00000&bidt=1&bidh=0&bidlaf=0&cb=6662.66.104.228.162.0&ver=1&w=&wy=&x=&y=&xy=&redirect=http%3A%2F%2Fwww.liverail.com]]></NonLinearClickThrough>
</NonLinear>
<TrackingEvents>
<Tracking event="acceptInvitation"><![CDATA[http://t4.liverail.com/?metric=accept&pos=1&coid=135&pid=1331&nid=1331&oid=228&olid=2281331&cid=8455&tpcid=&vid=&amid=&cc=default&pp=&vi=0&vv=&sg=&tsg=&pmu=0&pau=0&psz=0&ctx=&tctx=&coty=7&adt=0&did=&buid=&scen=&mca=&mma=&mct=0&url=http%3A%2F%2Fwww.iab.net%2Fguidelines%2F508676%2Fdigitalvideo%2Fvast%2Fvast_xml_samples&trid=53ea9957dc20a5.06241648&bidf=0.00000&bids=0.00000&bidt=1&bidh=0&bidlaf=0&cb=6662.66.104.228.162.0&ver=1&w=&wy=&x=&y=&xy=]]></Tracking>
<Tracking event="collapse"><![CDATA[http://t4.liverail.com/?metric=minimize&pos=1&coid=135&pid=1331&nid=1331&oid=228&olid=2281331&cid=8455&tpcid=&vid=&amid=&cc=default&pp=&vi=0&vv=&sg=&tsg=&pmu=0&pau=0&psz=0&ctx=&tctx=&coty=7&adt=0&did=&buid=&scen=&mca=&mma=&mct=0&url=http%3A%2F%2Fwww.iab.net%2Fguidelines%2F508676%2Fdigitalvideo%2Fvast%2Fvast_xml_samples&trid=53ea9957dc20a5.06241648&bidf=0.00000&bids=0.00000&bidt=1&bidh=0&bidlaf=0&cb=6662.66.104.228.162.0&ver=1&w=&wy=&x=&y=&xy=]]></Tracking>
</TrackingEvents>
</NonLinearAds>
</Creative>
<Creative sequence="1" id="8455">
<CompanionAds>
<Companion width="300" height="60">
<StaticResource creativeType="image/jpeg"><![CDATA[http://cdn.liverail.com/adasset/228/8455/300x60.jpg]]></StaticResource>
<TrackingEvents>
<Tracking event="creativeView"><![CDATA[http://t4.liverail.com/?metric=companion&pos=1&coid=135&pid=1331&nid=1331&oid=228&olid=2281331&cid=8455&tpcid=&vid=&amid=&cc=default&pp=&vi=0&vv=&sg=&tsg=&pmu=0&pau=0&psz=0&ctx=&tctx=&coty=7&adt=0&did=&buid=&scen=&mca=&mma=&mct=0&url=http%3A%2F%2Fwww.iab.net%2Fguidelines%2F508676%2Fdigitalvideo%2Fvast%2Fvast_xml_samples&trid=53ea9957dc20a5.06241648&bidf=0.00000&bids=0.00000&bidt=1&bidh=0&bidlaf=0&cb=6662.66.104.228.162.0&ver=1&w=&wy=&x=&y=&xy=]]></Tracking>
</TrackingEvents>
<CompanionClickThrough><![CDATA[http://t4.liverail.com/?metric=cclickthru&pos=1&coid=135&pid=1331&nid=1331&oid=228&olid=2281331&cid=8455&tpcid=&vid=&amid=&cc=default&pp=&vi=0&vv=&sg=&tsg=&pmu=0&pau=0&psz=0&ctx=&tctx=&coty=7&adt=0&did=&buid=&scen=&mca=&mma=&mct=0&url=http%3A%2F%2Fwww.iab.net%2Fguidelines%2F508676%2Fdigitalvideo%2Fvast%2Fvast_xml_samples&trid=53ea9957dc20a5.06241648&bidf=0.00000&bids=0.00000&bidt=1&bidh=0&bidlaf=0&cb=6662.66.104.228.162.0&ver=1&w=&wy=&x=&y=&xy=&redirect=http%3A%2F%2Fwww.liverail.com]]></CompanionClickThrough>
</Companion>
<Companion width="300" height="250">
<StaticResource creativeType="image/jpeg"><![CDATA[http://cdn.liverail.com/adasset/228/8455/300x250.jpg]]></StaticResource>
<TrackingEvents>
<Tracking event="creativeView"><![CDATA[http://t4.liverail.com/?metric=companion&pos=1&coid=135&pid=1331&nid=1331&oid=228&olid=2281331&cid=8455&tpcid=&vid=&amid=&cc=default&pp=&vi=0&vv=&sg=&tsg=&pmu=0&pau=0&psz=0&ctx=&tctx=&coty=7&adt=0&did=&buid=&scen=&mca=&mma=&mct=0&url=http%3A%2F%2Fwww.iab.net%2Fguidelines%2F508676%2Fdigitalvideo%2Fvast%2Fvast_xml_samples&trid=53ea9957dc20a5.06241648&bidf=0.00000&bids=0.00000&bidt=1&bidh=0&bidlaf=0&cb=6662.66.104.228.162.0&ver=1&w=&wy=&x=&y=&xy=]]></Tracking>
</TrackingEvents>
<CompanionClickThrough><![CDATA[http://t4.liverail.com/?metric=cclickthru&pos=1&coid=135&pid=1331&nid=1331&oid=228&olid=2281331&cid=8455&tpcid=&vid=&amid=&cc=default&pp=&vi=0&vv=&sg=&tsg=&pmu=0&pau=0&psz=0&ctx=&tctx=&coty=7&adt=0&did=&buid=&scen=&mca=&mma=&mct=0&url=http%3A%2F%2Fwww.iab.net%2Fguidelines%2F508676%2Fdigitalvideo%2Fvast%2Fvast_xml_samples&trid=53ea9957dc20a5.06241648&bidf=0.00000&bids=0.00000&bidt=1&bidh=0&bidlaf=0&cb=6662.66.104.228.162.0&ver=1&w=&wy=&x=&y=&xy=&redirect=http%3A%2F%2Fwww.liverail.com]]></CompanionClickThrough>
</Companion>
</CompanionAds>
</Creative>
</Creatives>
<Extensions />
</InLine>
</Ad>
</VAST>
<!-- 321 US_NEWJERSEY_NEWYORK_METUCHEN 08840 -->
</content>
</ad>
</boxb>
XML;
?>
If you want to get the XML-data, use asXML(),
echo $boxb->ad[0]->content->asXML();
And if you want to create your own XML document, you could use for example,
$myXML = new SimpleXMLElement($boxb->ad[0]->content->asXML());
echo $myXML->asXML();
Which would echo,
<!--?xml version="1.0"?-->
<content>
...
</content>
<?php
include 'boxb.php';
// Load string and parse as XML
$boxb = simplexml_load_string($xmlstr);
// Extract "content" element from loaded XML
$content = $boxb->ad->content;
// Convert extracted info into XML
$new_xml = $content->asXML();
// Send a header tag to the browser, stating that this info is XML
header('Content-type: application/XML');
// Print the actual XML
echo $new_xml;
?>
I want to be able to to delete a node tree if a specific child is empty, but seems to do something wrong?
Here is what I got:
$xml = new DOMDocument();
$xml->loadXML('<?xml version="1.0" encoding="ISO-8859-1"?>
<data>
<game id="1">
<opponent>Michael</opponent>
<oppid>1</oppid>
</game>
<game id="2">
<opponent>Trish</opponent>
<oppid>55</oppid>
</game>
<game id="3">
<opponent/>
<oppid>24</oppid>
</game>
<game id="4">
<opponent>Betty</opponent>
<oppid>12</oppid>
</game>
</data>
');
echo "<xmp>OLD \n". $xml->saveXML() ."</xmp>";
$xpath = new DOMXpath($xml);
foreach($xpath->query('//game') as $node) {
if($node->opponent == ''){
echo 'Test<br>';
$node->parentNode->removeChild($node);
}
}
echo "<xmp>NEW \n". $xml->saveXML() ."</xmp>";
I get 4 "Test" printed out and in the NEW xmp I get nothing? What am I doing wrong?
Please help and thanks in advance.
<?php
$xml = new DOMDocument();
$xml->loadXML('<?xml version="1.0" encoding="ISO-8859-1"?>
<data>
<game id="1">
<opponent>Michael</opponent>
<oppid>1</oppid>
</game>
<game id="2">
<opponent>Trish</opponent>
<oppid>55</oppid>
</game>
<game id="3">
<opponent/>
<oppid>24</oppid>
</game>
<game id="4">
<opponent>Betty</opponent>
<oppid>12</oppid>
</game>
</data>
');
echo "<xmp>OLD \n". $xml->saveXML() ."</xmp>";
$opNodes = $xml->getElementsByTagName('opponent');
foreach($opNodes as $node) {
$innerHtml = trim($node->nodeValue);
if(empty($innerHtml)){
$gameNode = $node->parentNode;
$gameNode->parentNode->removeChild($gameNode);
}
}
echo "<xmp>NEW \n". $xml->saveXML() ."</xmp>";
i wonder why it was not working... now it works .
Change your if condition to following:
if($node->opponent->nodeValue == '')
I'm trying to use an API with the following XML:
<movies>
<movie>
<images>
<image type="poster" url="http://cf1.imgobject.com/posters/b7a/4bc91de5017a3c57fe00bb7a/i-am-legend-original.jpg" size="original" width="675" height="1000" id="4bc91de5017a3c57fe00bb7a"/>
<image type="poster" url="http://cf1.imgobject.com/posters/b7a/4bc91de5017a3c57fe00bb7a/i-am-legend-mid.jpg" size="mid" width="500" height="741" id="4bc91de5017a3c57fe00bb7a"/>
<image type="poster" url="http://cf1.imgobject.com/posters/b7a/4bc91de5017a3c57fe00bb7a/i-am-legend-cover.jpg" size="cover" width="185" height="274" id="4bc91de5017a3c57fe00bb7a"/>
</images>
</movie>
</movies>
Can someone give me an example of the PHP code I should use to get the image url where size="cover"?
Thanks.
SimpleXML can do this quite, for lack of a better word, simply:
$xml = new SimpleXMLElement($str);
$xpath = $xml->xpath("/movies/movie/images/image[#size = 'cover']");
echo $xpath[0]['url'];
Load the xml with a XML Parser, DOMDocument, SimpleXML etc.
http://se.php.net/manual/en/refs.xml.php
Then you can use XPath to select the image.
http://www.w3schools.com/xpath/xpath_syntax.asp
XPath to grab movie with attribute size = cover
/movies/movie/images/image[#size=cover]
Looks like a good tutorial: http://ditio.net/2008/12/01/php-xpath-tutorial-advanced-xml-part-1/
<?php
$string = <<<XML
<?xml version='1.0'?>
<movies>
<movie>
<images>
<image type="poster" url="http://cf1.imgobject.com/posters/b7a/4bc91de5017a3c57fe00bb7a/i-am-legend-original.jpg" size="original" width="675" height="1000" id="4bc91de5017a3c57fe00bb7a"/>
<image type="poster" url="http://cf1.imgobject.com/posters/b7a/4bc91de5017a3c57fe00bb7a/i-am-legend-mid.jpg" size="mid" width="500" height="741" id="4bc91de5017a3c57fe00bb7a"/>
<image type="poster" url="http://cf1.imgobject.com/posters/b7a/4bc91de5017a3c57fe00bb7a/i-am-legend-cover.jpg" size="cover" width="185" height="274" id="4bc91de5017a3c57fe00bb7a"/>
</images>
</movie>
</movies>
XML;
$xml = simplexml_load_string($string);
foreach($xml->movie->images->image as $image) {
if(strcmp($image['size'],"cover") == 0)
echo $image['url'];
}
?>
$xml = simplexml_load_string($string2);
foreach($xml->movie->images->image as $image) {
if(strcmp($image['size'],"cover"))
// echo $image['url'];
?>
" width="200px" height="100px">