Get a part of content from a url - php

I don't know if you are able to do this, but...
Is there anyway to get a part of the content from a URL ?
Like if I have this:
<protected>false</protected>
<followers_count>6</followers_count>
<profile_background_color>00afe0</profile_background_color>
(The whole content is from Twitter)
But only want the <followers_count>6</followers_count> part?
Somebody who know how to do this?
(I hope you guys know what I mean by this)
PS. Anything above is JUST an example
PSS. Not just gona use this for xml, etc this format too (Which I don't know the name of)
Yes, I know that I could just use the file_get_contents-offset and maxlen thing, but the problem is, that I don't always know, where the part I'm looking for is.

You could use a native XML parser such as SimpleXML to find the value of a specific piece of content.

What you're looking at is called XML. PHP has a built-in XML parser which will allow you to extract the data you need.
$xml = simplexml_load_file(
'http://twitter.com/users/show.xml?screen_name=SlogaNator'
);
$follower_count = (int) $xml->followers_count; // int(6)

$data = file_get_contents('http://twitter.com/users/show.xml?screen_name=SlogaNator');
$xml = simplexml_load_string($data);
echo $xml->followers_count; # 6
"Let's give this guy minuses because he doesn't know you shouldn't parse XML with RegExp" version...
preg_match('#<followers_count>([0-9]+)</followers_count>#is', $xml, $matches);
echo $matches[1]; # 6

Related

Extract value from soap response

I need help to extract value from a soap response.
https://i.stack.imgur.com/djv5y.jpg
What i exactly need is:
$username=user
$message=success
Maybe include the SOAP response here, that would be helpful for those who come in the future. As for your question are you using a particular language? That would make it easier to answer.
If you are looking for a way to view use can use this URL: https://codebeautify.org/xmlviewer
Ok now that I see it, it's fairly easy
Assuming you have loaded the SOAP XML into a variable, lets call it $xml_string
$xml = simplexml_load_string($xml_string); // Load it as an object
$xmlarray = json_decode(json_encode($xml),TRUE); // Change it into an array
Then the variables you are looking for is in
$username = $xmlarray['UserName'];
$message = $xmlarray['response']['MESSAGE'];
BTW This solution is found here
PHP convert XML to JSON
I did it as an array as sometimes objects are a little hard to process. You can easily just do the first line and address it as an object. (If those are the only variables you need then an array works fine. Ex: the 'Plan' data will be messed up in an array as it appears twice)
There can be some issues such as the MESSAGE not appearing or the XML returning a failure but I think you should know how to code around missing datum.

Parsing deep XML with PHP SimpleXML and XPath

PHP noob here. I seem to be misunderstanding how to get the value of an XML node using XPath, and I haven't been able to find a StackOverflow answer that quite address what I'm doing wrong.
So, using RPG Geek's API, I'm trying to pull some information about the game Dread. (Here's a link to the URI.)
$rpggeekXML = simplexml_load_file('https://www.rpggeek.com/xmlapi/boardgame/166952?&stats=1');
$rating = $rpggeekXML->xpath('ratings/average');
$usersrated = $rpggeekXML->xpath('ratings/usersrated');
I know I'm successfully pulling in the rpggeek XML because if I do var_dump($rpggeekXML);, I can see all of the information I'm expecting. However, if I do var_dump($rating); or var_dump($usersrated);, it returns array(0) { }. So it seems I must be screwing up the XPath lines, but I can't figure out how. What am I doing wrong?
Use full path to find desired node:
$rating = $rpggeekXML->xpath( 'boardgame/statistics/ratings/average' );
echo $rating[0];
Collect all "average" nodes in document:
$rating = $rpggeekXML->xpath( '//average' );
echo $rating[0];
I think you xpath syntax is wrong. You can try this
$rpggeekXML = simplexml_load_file('https://www.rpggeek.com/xmlapi/boardgame/166952?&stats=1');
$rating = $rpggeekXML->xpath('//ratings/average');
$usersrated = $rpggeekXML->xpath('//ratings/usersrated');

Use XML tag attribute as PHP variable and use it in HTTP request

Is there any way to save an XML attribute as a PHP variable and automatically place it in another http request? Or is there a better way to do that?
Basically, I send a server an http request, the code I get back looks something like this:
<tag one="info" two="string">
I need to save the string in attribute two and insert it in an http request that looks something like this:
http://theserver.com/request?method=...&id=123456
The '123456' ID needs to be the string in attribute 'two'.
Any help would be appreciated!
Thanks,
Jane
If you are 100% entirely absolutely completely TOTALLY sure that the content will always have that exact format, you can probably use regex as the other answers have suggested.
Otherwise, DOM isn't very hard to manage...
$dom = new DOMDocument;
$dom->loadXML($yourcontent);
$el = $dom->getElementsByTagName('A')->item(0); // presuming your tag is the only element in the document
if ($el) {
$id = $el->getAttribute('id');
}
$url = 'http://theserver.com/request?method=...&id=' . $id;
If you have a real example of the XML that you'll receive, please do post it and I'll adapt this answer for it.
If you can... send it in JSON. If you can't, and the only thing that is returned is that wee snippet, then I'd use regex to pull out the value.
Something like /.*two="([^"]+)".*/ should match everything, replace matches with '$1'
Otherwise use simplexml.
You could use:
<?php
$string = '<tag one="info" two="123456">';
if (preg_match('/<tag one="[^"]*" two=\"([^"]*)\">/',$string,$match)) {
$url = 'http://theserver.com/request?method=...&id=' . $match[1];
echo $url;
}
?>

PHP: How can I access this XML entity when its name contains a reserved word?

I'm trying to parse this feed: http://musicbrainz.org/ws/1/artist/c0b2500e-0cef-4130-869d-732b23ed9df5?type=xml&inc=url-rels
I want to grab the URLs inside the 'relation-list' tag.
I've tried fetching the URL with PHP using simplexml_load_file(), but I can't access it using $feed->artist->relation-list as PHP interprets "list" as the list() function.
I have a feeling I'm going about this wrong (not much XML experience), and even if I was able to get hold of the elements I want, I don't know how to extract their attributes (I just want the type and target fields).
Can anyone gently nudge me in the right direction?
Thanks.
Matt
Have a look at the examples on the php.net page, they actually tell you how to solve this:
// $feed->artist->relation-list
$feed->artist->{'relation-list'}
To get an attribute of a node, just use the attribute name as array index on the node:
foreach( $feed->artist->{'relation-list'}->relation as $relation ) {
$target = (string)$relation['target'];
$type = (string)$relation['type'];
// Do something with it
}
(Untested)

PHP get external page content

i get the html from another site with file_get_contens, my question is how can i get a specific tag value?
let's say i have:
<div id="global"><p class="paragraph">1800</p></div>
how can i get paragraph's value? thanks
If the example is really that trivial you could just use a regular expression. For generic HTML parsing though, PHP has DOM support:
$dom = new domDocument();
$dom->loadHTML("<div id=\"global\"><p class=\"paragraph\">1800</p></div>");
echo $dom->getElementsByTagName('p')->item(0)->nodeValue;
You need to parse the HTML. There are several ways to do this, including using PHP's XML parsing functions.
However, if it is just a simple value (as you asked above) I would use the following simple code:
// your content
$contents='<div id="global"><p class="paragraph">1800</p></div>';
// define start and end position
$start='<div id="global"><p class="paragraph">';
$end='</p></div>';
// find the stuff
$contents=substr($contents,strpos($contents,$start)+strlen($start));
$contents=substr($contents,0,strpos($contents,$end));
// write output
echo $contents;
Best of luck!
Christian Sciberras
(tested and works)
$input = '<div id="global"><p class="paragraph">1800</p></div>';
$output = strip_tags($input);
preg_match_all('#paragraph">(.*?)<#is', $input, $output);
print_r($output);
Untested.

Categories