Jane
Jane

Reputation: 987

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

Upvotes: 1

Views: 550

Answers (3)

lonesomeday
lonesomeday

Reputation: 237865

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.

Upvotes: 3

AndersTornkvist
AndersTornkvist

Reputation: 2629

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

?>

Upvotes: 1

Aaria Carter-Weir
Aaria Carter-Weir

Reputation: 1679

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.

Upvotes: 1

Related Questions