Extract some CDATA from a xml file with PHP - php

I've to extract some data from a xml file.
In this file there are some tags that contains CDATA content and I don't try to extract this contents.
The file is like this:
<treeplat>
<ad>
<id>965192-VR</id>
<region>VT</region>
<description>
<![CDATA[
Orte scalo. Vicinissimo alla stazione, in zona tranquilla e panoramica, proponiamo appartamento di recente costruzione così composto: ingresso, salone con ampio angolo cottura e balcone, disimpegno, camera matrimoniale con balcone, cantina e posto auto.
]]>
</description>
<pictures>
<picture>
<picture_url>
<![CDATA[
http://www.immobile.net/media/foto/1440/9f352078-885d-4281-a36d-1d22b3cbdcd9-x.jpg
]]>
</picture_url>
</picture>
<picture>
<picture_url>
<![CDATA[
http://www.immobile.net/media/foto/1440/992a5c0f-62dd-48f2-8c41-9b8ee9e06ca9-x.jpg
]]>
</picture_url>
</picture>
<picture>
<picture_url>
<![CDATA[
http://www.immobile.net/media/foto/1440/a61b4705-ed0a-494b-86fc-e92bb4c916e7-x.jpg
]]>
</picture_url>
</picture>
<picture>
<picture_url>
<![CDATA[
http://www.immobile.net/media/foto/1440/d1817d53-51fa-43dc-baf9-d3457963e694-x.jpg
]]>
</picture_url>
</picture>
<picture>
<picture_url>
<![CDATA[
http://www.immobile.net/media/foto/1440/8299cd3e-f253-4c83-9629-fb77131a2efb-x.jpg
]]>
</picture_url>
</picture>
</pictures>
</ad>
</treeplat>
I parse the xml file in this way:
$xml = simplexml_load_file(storage_path('app'.DIRECTORY_SEPARATOR.'public'.DIRECTORY_SEPARATOR.$percorso_file.'test.xml'));
foreach ($xml->ad as $immobile) {
...
}
My problem is tag. I try to extract the first only using this code:
$picture_url_1 = (string)$immobile->pictures->picture->picture_url
but I don't try to extract every picture_url.
How can I parse all the pictures tag?
Many thank's!

you are looping over the wrong variable. what you need is:
$pictures = $xml->ad->pictures->picture;
foreach ($pictures as $picture) {
echo $picture->picture_url;
}
(you can replace echo with whatever command you need)

Gilad almost had it!
$pictures = $xmlData->ad->pictures;
foreach($pictures as $picture)
{
foreach($picture as $pic)
{
echo (string) $pic->picture_url;
}
}
https://3v4l.org/990NR

Related

php create xml CDATA on loop

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);

XML to MySQL when xml file has multiple matching fields

I've been doing some work on an XML to Mysql using load XML. I have been successful with itin the past. The difference with the latest effort is that we have multiple occurrences of a field-name in the MySQL. A sample of this is below:
<row>
<pictures>
<picture name="Photo 1">
<filename>image1.jpg</filename>
</picture>
<picture name="Photo 2">
<filename>image2.jpg</filename>
</picture>
<picture name="Photo 4">
<filename>image3.jpg</filename>
</picture>
<picture name="Photo 3">
<filename>image4.jpg</filename>
</picture>
<picture name="Photo 7">
<filename>image5.jpg</filename>
</picture>
<picture name="Photo 6">
<filename>image6.jpg</filename>
</picture>
<picture name="Photo 5">
<filename>image7.jpg</filename>
</picture>
<picture name="Photo 8">
<filename>image8.jpg</filename>
</picture>
<picture name="Photo 9">
<filename>image9.jpg</filename>
</picture>
</pictures>
</row>
I need to import this into a MySQL table with the fields:
picture1
picture2
picture3
picture4
picture5
picture6
picture7
picture8
picture9
As you can see, the 'name' attribute doesn't necessarily occur in the correct order, so I need them to simply be inserted in order. So the first <filename> to go to picture1, the second <filename> to picture2 etc..
What is currently being achieved is that I always end up with the last <picture> entry in the list being in the table. This is I assume because the filed is being overwritten each time.
Any ideas how to achieve this? I have found similar queries to this but no answers as yet and have been looking for a good while. The rest of the file is loading fine as they have unique field-names and can easily be mapped to a MySQL column, but I am struggling with this one.
As the XML does not match the format you aim for you need to transform it first. Traditionally this is done with XSLT but you can also do this with XMLReader and XMLWriter in PHP which has the benefit that it does not require to keep the whole XML document(s) in memory.
The XMLReaderIterator package has support for such operations, an example is already given with the library.
Creating a modification of that example code by taking your specific case and an exemplary input file named pictures.xml and keeping the output to the standard-output for demonstration purposes allows me to quote the following excerpt:
[... starts like examples/read-write.php]
/** #var $iterator XMLWritingIteration|XMLReaderNode[] */
$iterator = new XMLWritingIteration($writer, $reader);
$writer->startDocument();
$rename = ['row' => 'resultset', 'pictures' => 'row'];
$trimLevel = null;
$pictureCount = null;
foreach ($iterator as $node) {
$name = $node->name;
$isElement = $node->nodeType === XMLReader::ELEMENT;
$isEndElement = $node->nodeType === XMLReader::END_ELEMENT;
$isWhitespace = $node->nodeType === XMLReader::SIGNIFICANT_WHITESPACE;
if (($isElement || $isEndElement) && $name === 'filename') {
// drop <filename> opening and closing tags
} elseif ($isElement && $name === 'picture') {
$writer->startElement('field');
$writer->writeAttribute('name', sprintf('picture%d', ++$pictureCount));
$trimLevel = $node->depth;
} elseif ($trimLevel && $isWhitespace && $node->depth > $trimLevel) {
// drop (trim) SIGNIFICANT_WHITESPACE
} elseif ($isElement && isset($rename[$name])) {
$writer->startElement($rename[$name]);
if ($rename[$name] === 'row') {
$pictureCount = 0;
}
} else {
$iterator->write();
}
}
This is one XMLWritingIteration that is composed of an XMLReader and XMLWriter object. That iteration allows you to take over everything from the input document (via $iterator->write()) and do the needed changes only on occasions:
drop the <filename> and </filename> tags
create <field> elements with the correct name attributes to have the pictures in document order (Mysql XML nomenclature)
drop significant whitespace as <filename> tags are dropped as well
rename the document element from <row> to <resultset> (Mysql XML nomenclature)
rename the <pictures> element to <row> (again Mysql XML nomenclature)
the counter for the picture fields is reset per each (output) row
everything else is kept as-is
Such a transformation results in the following example output with the XML presented in your question:
<?xml version="1.0"?>
<resultset>
<row>
<field name="picture1">image1.jpg</field>
<field name="picture2">image2.jpg</field>
<field name="picture3">image3.jpg</field>
<field name="picture4">image4.jpg</field>
<field name="picture5">image5.jpg</field>
<field name="picture6">image6.jpg</field>
<field name="picture7">image7.jpg</field>
<field name="picture8">image8.jpg</field>
<field name="picture9">image9.jpg</field>
</row>
</resultset>
For more information about the XML format used by Mysql, please see the Mysql documentation for the --xml commandline switch which describes the standard XML output format which can be read in by LOAD XML.
For this little example you could as well use XSLT as there would be no problem to do the whole transformation in memory. But if you need to look for memory (which can happen if you deal with XML database dumps), the XMLWritingIteration allows iteration based XML transformation with an XML Pull parser (XMLReader) and forward-only XML output via XMLWriter.
And here is the XSLT solution. As information, XSLT is a declarative special-purpose language to transform, re-style, and restructure XML documents in various formats for end use purposes. PHP maintains an XSLT processor. Be sure to uncomment out extension=php_xsl.dll
XLST (accommodates image numbers greater than two digits)
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output version="1.0" encoding="UTF-8"/>
<xsl:template name="picturesort" match="pictures" >
<row>
<pictures>
<xsl:for-each select="picture">
<xsl:variable name="numkey"
select="substring-after(substring-before(filename, '.'), 'e')"/>
<picture name="{../picture[substring-after(#name, ' ') = $numkey]/#name}">
<xsl:copy-of select="filename"/>
</picture>
</xsl:for-each>
</pictures>
</row>
</xsl:template>
</xsl:stylesheet>
XML OUTPUT
<?xml version="1.0" encoding="UTF-8"?>
<row>
<pictures>
<picture name="Photo 1">
<filename>image1.jpg</filename>
</picture>
<picture name="Photo 2">
<filename>image2.jpg</filename>
</picture>
<picture name="Photo 3">
<filename>image3.jpg</filename>
</picture>
<picture name="Photo 4">
<filename>image4.jpg</filename>
</picture>
<picture name="Photo 5">
<filename>image5.jpg</filename>
</picture>
<picture name="Photo 6">
<filename>image6.jpg</filename>
</picture>
<picture name="Photo 7">
<filename>image7.jpg</filename>
</picture>
<picture name="Photo 8">
<filename>image8.jpg</filename>
</picture>
<picture name="Photo 9">
<filename>image9.jpg</filename>
</picture>
</pictures>
</row>
PHP
<?php
// Load the XML source
$xml = new DOMDocument;
$xml->load('C:/Path/To/XMLfile.xml');
$xsl = new DOMDocument;
$xsl->load('C:/Path/To/XSLfile.xsl');
// Configure the transformer
$proc = new XSLTProcessor;
$proc->importStyleSheet($xsl);
// Transform XML source
$newXml = $proc->transformToXML($xml);
echo $newXml;
// Save output to file
file_put_contents("C:/Path/To/NewXMLfile.xml", $newXml);
?>
Possible way:
iterate over all <picture> in a <row>
build an associative array with key = name and value = filename
sort array by keys
feed the array to your DB

PHP XPath xml file cdata error

I'm trying to get data from a XML file through xPath.
This is the XML:
<item>
<title>
51-årig stukket i maven: Klapper i over for politiet
</title>
<link>
http://newsbreak.dk/51-aarig-ringede-om-hjaelp-efter-knivstik-nu-tier-han/
</link>
<pubDate>Tue, 20 Jan 2015 09:19:46 +0000</pubDate>
<description>
<![CDATA[
<img width="600" height="400" src="http://newsbreak.dk/wp-content/uploads/2015/01/politi44.jpg" class="attachment-big" alt="Foto: Colourbox (genrefoto)" /><br />51-årig mand vil ikke tale med politiet, selvom han selv ringede til ordensmagten for at få hjælp til knivstik
]]>
</description>
<category>
<![CDATA[ A-historier ]]>
</category>
<category>
<![CDATA[ Krim ]]>
</category>
<guid>
http://newsbreak.dk/51-aarig-ringede-om-hjaelp-efter-knivstik-nu-tier-han/
</guid>
</item>
This is the PHP:
$titelQuery = $xpath->query("//item/title/text()");
$itemQuery = $xpath->query("//item");
$linkQuery = $xpath->query("//item/guid/text()");
$imageQuery = $xpath->query("//item/description/text()");
I get the title and link correctly , but when im trying to get the "description" part, im only getting the text after the image tag like so:
<br />51-årig mand vil ikke tale med politiet, selvom han selv ringede til ordensmagten for at få hjælp til knivstik
]]>
Just target that <description> node, then use ->nodeValue:
$imageQuery = $xpath->query("//item/description");
echo $imageQuery->item(0)->nodeValue;
Sample Output
Using ->evaluate() will work as well:
echo $xpath->evaluate('string(//item/description)');

PHP - Parse XML contained within XML element and Output into XML doc

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;
?>

Get image from XML and display with PHP?

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">

Categories