simpleXML get node child based on attribute [duplicate] - php

This question already has answers here:
SimpleXML: Selecting Elements Which Have A Certain Attribute Value
(2 answers)
Implementing condition in XPath [duplicate]
(2 answers)
Closed 9 years ago.
I am trying to parse out the value of a node I am referencing by one of its attributes. but I am not sure of the syntax
XML:
<data>
<poster name="E-Verify" id="everify">
<full_image url="e-verify-swa-poster.jpg"/>
<full_other url=""/>
</poster>
<poster name="Minimum Wage" id="minwage">
<full_image url="minwage.jpg"/>
<full_other url="spa_minwage.jpg"/>
</poster>
</data>
here is where I want to get the url value of full_image where poster id equal to minwage:
$xml = simplexml_load_file('PosterData.xml');
$main_url = $xml->full_image[name] where poster[id] = "minwage";
//something like that.
echo $main_url;
Result: minwage.jpg
If anyone has any resources that cover this stuff please share.

You should be able to use SimpleXMLElement::xpath() to run an xpath query on a simple XML document.
$xml = simplexml_load_file('PosterData.xml');
$main_url = $xml->xpath('name[#id="minwage"]/full_image')[0];
echo $main_url;

Simply loop the poster elements and remember to cast the attribute values to strings, since you want to compare them (and probably output them) as strings:
$xml = simplexml_load_file('PosterData.xml');
foreach ($xml->poster as $poster) {
if ((string) $poster['id'] == 'minwage') {
echo (string) $poster->full_image['url'];
}
}

You can use:
$object = simplexml_load_string('<data><poster name="E-Verify" id="everify"><full_image url="e-verify-swa-poster.jpg"/><full_other url=""/></poster><poster name="Minimum Wage" id="minwage"><full_image url="minwage.jpg"/><full_other url="spa_minwage.jpg"/></poster></data>');
foreach ($object as $value) {
echo "URL: ".$value->full_image->attributes();
echo "<br>";
}
Either use simplexml_load_file('Some external file.xml') if calling external file.

Related

How do I parse a specific child of xml output using simplexml? [duplicate]

This question already has answers here:
SimpleXML: Selecting Elements Which Have A Certain Attribute Value
(2 answers)
Closed 5 years ago.
I wish to parse this XML output, but only fetch the value for the "doi" record (e.g. 10.1038/onc.2012.390)
<ArticleIdList>
<ArticleId IdType="pubmed">22986524</ArticleId>
<ArticleId IdType="pii">onc2012390</ArticleId>
<ArticleId IdType="doi">10.1038/onc.2012.390</ArticleId>
</ArticleIdList>
Can some advise me how to accomplish this?
I've used
$xml = simplexml_load_file($query) or die("Error, feed not loading");
to create the object, but could not figure out the right syntax to move fw..
Thanks!
With SimpleXMLElement::xpath ( string $path ) function:
$xml = simplexml_load_file($query) or die("Error, feed not loading");
$article_doi = (string) $xml->xpath('//ArticleId[#IdType="doi"]')[0];
print_r($article_doi);
The output:
10.1038/onc.2012.390
http://php.net/manual/en/simplexmlelement.xpath.php

How to get value with simplexml? [duplicate]

This question already has answers here:
SimpleXML: Selecting Elements Which Have A Certain Attribute Value
(2 answers)
Closed 8 years ago.
I have XML-file and i try to get value. I need value 12345 from variable media_id. How i can get it with php and simplexml?
<?xml version="1.0" encoding="UTF-8"?>
<Playerdata>
<Clip>
<MediaType>video_episode</MediaType>
<Duration>5400</Duration>
<PassthroughVariables>
<variable name="media_type" value="video_episode"/>
<variable name="media_id" value="12345"/>
</PassthroughVariables>
</Clip>
</Playerdata>
I have now only:
$xml = simplexml_load_file("file.xml");
Try this:
$xml = simplexml_load_file("file.xml");
$variable = $xml->xpath('//variable[#name="media_id"]')[0];
echo $variable["value"];
You can load your XML file into Simplexml which will parse it and return an SimpleXML object.
$xml = simplexml_load_file('path/to/file.xml');
//then you should be able to access the data through objects
$passthrough = $xml->Clip->PassthroughVariables;
//because you have many children in the PassthroughVariables you'll need to iterate
foreach($passthrough as $p){
//to get the attributes of each node you'll have to call attributes() on the object
$attributes = $p->attributes();
//now we can iterate over each attribute
foreach($attributes as $a){
//SimpleXML will assume each data type is a SimpleXMLElement/Node
//so we need to cast it for comparisons
if((String)$a->name == "media_id"){
return (int)$a->value;
}
}
}
The SimpleXMLElement documentation is probably a good starting point when it comes to working with the SimpleXMLObject. http://uk1.php.net/manual/en/class.simplexmlelement.php
Here is w/o Xpath
$xml = simplexml_load_file('file.xml');
$value = (int) $xml->Clip->PassthroughVariables->variable[1]['value'];

Adding XML children to start of XML data/file [duplicate]

This question already has answers here:
PHP SimpleXML: insert node at certain position
(2 answers)
Closed 8 years ago.
I'm trying to add a comment list to a page using an xml file. I'd like to list the comments most recent first, so when a new comment is added, I'd like to add it to the start of the xml. addChild appends to the end, so that's no good, and I can't get my head around the the DOMNode insert_before method, as I want to add it at the start before every other occurrence of a child (and I can't find an example anywhere that does this - weird).
xml file looks like;
<comments>
<comment>
<date>20130625</date>
<name>Jocky Wilson</name>
<text>Something about darts presumably</text>
</comment>
<comment>
<date>20130622</date>
<name>Jacky Wilson</name>
<text>It was reet petite etc</text>
</comment>
</comments>
I create the file initially with;
<?php
$xmlData = "< load of xml etc...";
$xml = new SimpleXMLElement($xmlData);
file_put_contents("comments.xml", $xml->asXML());
?>
And that works fine. Any suggestions at all gratefully received.
As an alternative to the solutions mentioned in the comments:
use addChild, let it add the node wherever it wants to, sort it by <date> and echo it:
$xml = simplexml_load_string($x); // assume XML in $x
$comments = $xml->xpath("//comment");
$field = 'date';
sort_obj_arr($comments, $field, SORT_DESC);
var_dump($comments);
// function sort_obj_array written by GZipp, see link below
function sort_obj_arr(& $arr, $sort_field, $sort_direction) {
$sort_func = function($obj_1, $obj_2) use ($sort_field, $sort_direction) {
if ($sort_direction == SORT_ASC) {
return strnatcasecmp($obj_1->$sort_field, $obj_2->$sort_field);
} else {
return strnatcasecmp($obj_2->$sort_field, $obj_1->$sort_field);
}
};
usort($arr, $sort_func);
}
see GZipp's original function: Sorting an array of SimpleXML objects

Linked in xml response to php variables [duplicate]

This question already has answers here:
How do you parse and process HTML/XML in PHP?
(31 answers)
Closed 9 years ago.
i am getting this result from my linked in connect script,
<person>
<email-address>xzenia1#gmail.com</email-address>
<picture-url>http://m3.licdn.com/mpr/mprx/0_UiHHf6SiF4yuBerHUkfUfkshFpomUIrHMbpBf5Iy4sOYk7FecL4XTLxtdAEl42AXsho9hGzDtRBl</picture-url>
</person>
this is the php call
$xml_response = $linkedin->getProfile("~:(email-address,picture-url)");
how to make them assign to separate PHP variable.
You can load your xml as string with simplexml_load_string and then loop in it to get all data
$xml = simplexml_load_string($xml_response);
foreach($xml as $key => $val)
{
echo "$key=>$val<br>" . "\n";
}
This will output
email-address=>xzenia1#gmail.com
picture-url=>http://m3.licdn.com/mpr/mprx/0_UiHHf6SiF4yuBerHUkfUfkshFpomUIrHMbpBf5Iy4sOYk7FecL4XTLxtdAEl42AXsho9hGzDtRBl
Live sample
Try,
$xml = (array)simplexml_load_string($xml_response);
echo $email=$xml['email-address'];
echo $picture=$xml['picture-url'];
$xml = simplexml_load_string($linkedin->getProfile("~:(email-address,picture-url)"));
echo $xml->{'email-address'}[0] . "<br />";
echo $xml->{'picture-url'}[0];
simplexmldoesn't like - in node names, therefore use $xml->{'email-address'} instead of $xml->email-address.
use index [0] on both nodes, just in case, if one day your simplexml object would contain more than one <person> node...
see it working: http://codepad.viper-7.com/dQQ6sa

simpleXML creating a foreach [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
foreach and simplexml
I have got my XML document loading correct but I am unsure how I can create a simple foreach were I can have [PictureHref] [Title] and [PriceDisplay] loaded for each item given in the feed.
I cannot find a clear example in the documentation.
XML Example
Currently my PHP code consists of the following:
$mainUrl = 'http://api.trademe.co.nz/v1/Member/{id}/Listings/All.xml';
$xmlFeed = simplexml_load_file($mainUrl);
XML
<Listings xmlns="http://api.trademe.co.nz/v1" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<TotalCount>1</TotalCount>
<Page>1</Page>
<PageSize>1</PageSize>
<List>
<Listing>
<ListingId>527496168</ListingId>
<Title>Clifftop Resort style Living with stunning aspect</Title>
<Category>0350-5748-3399-</Category>
<StartPrice>0</StartPrice>
<StartDate>2012-10-26T21:24:47.073Z</StartDate>
<EndDate>2012-12-21T21:24:47.073Z</EndDate>
<ListingLength i:nil="true" />
<HasGallery>true</HasGallery>
<AsAt>2012-10-28T22:48:47.409946Z</AsAt>
<CategoryPath>/Trade-me-property/Residential/For-sale</CategoryPath>
<PictureHref>http://images.trademe.co.nz/photoserver/thumb/10/239043710.jpg</PictureHref>
<RegionId>2</RegionId>
<Region>Auckland</Region>
<Suburb>North Shore</Suburb>
<NoteDate>1970-01-01T00:00:00Z</NoteDate>
<ReserveState>NotApplicable</ReserveState>
<IsClassified>true</IsClassified>
<GeographicLocation>
<Latitude>-36.5681333</Latitude>
<Longitude>174.6936265</Longitude>
<Northing>5951700</Northing>
<Easting>1751547</Easting>
<Accuracy>Address</Accuracy>
</GeographicLocation>
<PriceDisplay>To be auctioned</PriceDisplay>
</Listing>
</List>
</Listings>
All you need is
$url = simplexml_load_file("__YOUR__URL___");
$listing = $url->List->Listing;
echo "<pre>";
echo $listing->PictureHref, PHP_EOL;
echo $listing->Title, PHP_EOL;
echo $listing->PriceDisplay, PHP_EOL;
While I'd recommend the use of DOMDocument instead of SimpleXML, here's how you'd do that in SimpleXML:
$data = array();
foreach($xmlFeed->List as $item) {
$data[] = array(
(string) $item->Listing->PictureHref,
(string) $item->Listing->Title,
(string) $item->Listing->PriceDisplay
);
}
You can see it (sorta, I had to change some things) at CodePad

Categories