0

I thought this was an easy task, but apparently not.

   $dom = new DOMDocument();
   $dom->loadHTMLFile("myhtml.html");
   $timestamp = $dom->getElementById('timestamp');
   $timestamp = $dom->saveHTML($timestamp);
   $matches_out = array();
   if (preg_match_all('/<div id="timestamp">(.*)<\/div>/', $timestamp, $matches_out)) {
  $timestamp = $matches_out[0];
  }
  echo $timestamp;

I need to get the value out of the array and store it in the $timestamp variable. When I use print_r() I get Array ( [0] =>1422936994). I thought that mean to get my timestamp I just do $matches_out[0] because I can see it right there on the zero index, or am I missing something.

Trying to echo it out gets me this: Notice: Array to string conversion in C:\xampp\htdocs\myscript.php on line 10

4
  • i dont really understand the question, but yes, $timestamps is now array, when you do echo, it will display the error Commented Feb 3, 2015 at 13:54
  • but I thought you could get a string from an array using the index number, see here: stackoverflow.com/a/16876209 Commented Feb 3, 2015 at 13:56
  • if you look at preg_match_all() documentation, then you will realize that $matches_out is Array of all matches in multi-dimensional array ordered according to flags. so please do not expect $matches_out[0] is string now Commented Feb 3, 2015 at 13:58
  • I don't understand why you even want to use preg_match_all. Why not use the DOMDocument object methods? For example the getElementsByTagName method. Commented Feb 3, 2015 at 14:07

3 Answers 3

1

$matches_out is multi-dimensional array. So your correct code would be something like $matches_out[0][0]. Please inspect your array again to make sure you get the correct value.

See preg_match_all

Sign up to request clarification or add additional context in comments.

2 Comments

How do I store this value in a variable not merely for echoing but for performing mathematical operations on?
Please use $var_name = $matches_out[0][0];
1

$timestamp is an array. So instead of

echo $timestamp;

do

echo $timestamp[0];

And once again if you don't want to have indexes:

$newTimestamp = $timestamp[0];
echo $newTimestamp;

Comments

0

You are calling the wrong item, timestamp the variable has become an array call it the same way like this

$timestamp[0]

1 Comment

is there a way to assign that, $timestamp[0] to an actual variable so I can avoid using index numbers...? Or if I want to say, perform a mathematical operation on the timestamp do I have to use, $myResult = $timestamp[0] - 100; because the above just gets me -100

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.